query
stringlengths
10
3.85k
ru_query
stringlengths
9
3.76k
document
stringlengths
17
430k
metadata
dict
negatives
listlengths
97
100
negative_scores
listlengths
97
100
document_score
stringlengths
5
10
document_rank
stringclasses
2 values
Deprecated: Use RunOpsReq.ProtoReflect.Descriptor instead.
Устарело: используйте RunOpsReq.ProtoReflect.Descriptor вместо этого.
func (*RunOpsReq) Descriptor() ([]byte, []int) { return file_api_ops_proto_rawDescGZIP(), []int{15} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (*PatchCollectorsRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{161}\n}", "func (*PatchTasksRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{154}\n}", "func (*UpdateTensorboardRunRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_aiplatform_v1_tensorboard_service_proto_rawDescGZIP(), []int{24}\n}", "func (*GetTensorboardRunRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_aiplatform_v1_tensorboard_service_proto_rawDescGZIP(), []int{19}\n}", "func (*RunWorkflowRequest) Descriptor() ([]byte, []int) {\n\treturn file_pkg_flow_grpc_instances_proto_rawDescGZIP(), []int{15}\n}", "func (*RevokeJobRequest) Descriptor() ([]byte, []int) {\n\treturn file_pkg_noderpc_proto_feeds_manager_proto_rawDescGZIP(), []int{20}\n}", "func (*PatchWorkflowsRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{131}\n}", "func (*PatchConceptsRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{34}\n}", "func (*PatchAnnotationsRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{4}\n}", "func (*CreateTensorboardRunRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_aiplatform_v1_tensorboard_service_proto_rawDescGZIP(), []int{18}\n}", "func (*RevokeTokensRequest) Descriptor() ([]byte, []int) {\n\treturn file_token_proto_rawDescGZIP(), []int{17}\n}", "func (*PatchWorkflowVersionsRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{143}\n}", "func (*DeleteTensorboardRunRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_aiplatform_v1_tensorboard_service_proto_rawDescGZIP(), []int{25}\n}", "func (*UpdateTensorboardRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_aiplatform_v1_tensorboard_service_proto_rawDescGZIP(), []int{4}\n}", "func (*ModifyRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_engine_proto_rawDescGZIP(), []int{10}\n}", "func (*CalculatorRequest) Descriptor() ([]byte, []int) {\n\treturn file_basicpb_unary_api_proto_rawDescGZIP(), []int{4}\n}", "func (*DeleteCollectorsRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{162}\n}", "func (*ValidateRequest) Descriptor() ([]byte, []int) {\n\treturn file_protobuf_clusrun_proto_rawDescGZIP(), []int{17}\n}", "func (*RunRequest) Descriptor() ([]byte, []int) {\n\treturn file_command_proto_rawDescGZIP(), []int{9}\n}", "func (*PatchKeysRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{74}\n}", "func (*GenerateProductMixIdeasRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_ads_googleads_v2_services_reach_plan_service_proto_rawDescGZIP(), []int{7}\n}", "func (*CMsgClientToGCPlayerStatsRequest) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_client_proto_rawDescGZIP(), []int{143}\n}", "func (*GetModelEvaluationRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_automl_v1_service_proto_rawDescGZIP(), []int{18}\n}", "func (*RevokeFactoryCertificateRequest) Descriptor() ([]byte, []int) {\n\treturn file_token_proto_rawDescGZIP(), []int{15}\n}", "func (*RefreshRequest) Descriptor() ([]byte, []int) {\n\treturn file_cloudprovider_externalgrpc_protos_externalgrpc_proto_rawDescGZIP(), []int{16}\n}", "func (*WatchProvisioningApprovalRequestsRequest) Descriptor() ([]byte, []int) {\n\treturn edgelq_devices_proto_v1alpha_provisioning_approval_request_service_proto_rawDescGZIP(), []int{7}\n}", "func (*PatchAnnotationsStatusRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{5}\n}", "func (*PatchInputsRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{59}\n}", "func (*RunRequest) Descriptor() ([]byte, []int) {\n\treturn file_coco_proto_rawDescGZIP(), []int{3}\n}", "func (*ApplyRequest) Descriptor() ([]byte, []int) {\n\treturn file_github_com_containerd_containerd_api_services_diff_v1_diff_proto_rawDescGZIP(), []int{0}\n}", "func (*CreateAlterRequest) Descriptor() ([]byte, []int) {\n\treturn file_grpc_exercicio_proto_rawDescGZIP(), []int{1}\n}", "func (*DiagnoseRuntimeRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_notebooks_v1_managed_service_proto_rawDescGZIP(), []int{14}\n}", "func (*ScheduleWorkloadRequest) Descriptor() ([]byte, []int) {\n\treturn file_api_protoc_api_schedule_workload_request_message_proto_rawDescGZIP(), []int{0}\n}", "func (*TaskUpdateRequest) Descriptor() ([]byte, []int) {\n\treturn file_pkg_protobuf_v1_task_proto_rawDescGZIP(), []int{2}\n}", "func (*ApplyWorkspaceEditRequest) Descriptor() ([]byte, []int) {\n\treturn file_protocol_rpc_rpc_proto_rawDescGZIP(), []int{86}\n}", "func (*DiffRequest) Descriptor() ([]byte, []int) {\n\treturn file_github_com_containerd_containerd_api_services_diff_v1_diff_proto_rawDescGZIP(), []int{2}\n}", "func (*GetServiceRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_appengine_v1_appengine_proto_rawDescGZIP(), []int{6}\n}", "func (*UpdatePermissionRequest) Descriptor() ([]byte, []int) {\n\treturn file_pkg_role_pb_request_proto_rawDescGZIP(), []int{9}\n}", "func (*RestartServicesRequest) Descriptor() ([]byte, []int) {\n\treturn file_orc8r_protos_magmad_proto_rawDescGZIP(), []int{9}\n}", "func (*PatchModelsRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{80}\n}", "func (*PatchConceptLanguagesRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{50}\n}", "func (*EventsRequest) Descriptor() ([]byte, []int) {\n\treturn file_org_apache_beam_model_pipeline_v1_beam_runner_api_proto_rawDescGZIP(), []int{23}\n}", "func (*GetTensorboardRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_aiplatform_v1_tensorboard_service_proto_rawDescGZIP(), []int{1}\n}", "func (*UpdateIngressRuleRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_appengine_v1_appengine_proto_rawDescGZIP(), []int{26}\n}", "func (*UpdateTaskRequest) Descriptor() ([]byte, []int) {\n\treturn file_github_com_containerd_containerd_runtime_v1_shim_v1_shim_proto_rawDescGZIP(), []int{15}\n}", "func (*AddRequest) Descriptor() ([]byte, []int) {\n\treturn file_grpc_calculator_proto_calc_proto_rawDescGZIP(), []int{0}\n}", "func (*DeleteWorkflowVersionsRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{142}\n}", "func (*DeleteWorkflowRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{132}\n}", "func (*DeleteRequest) Descriptor() ([]byte, []int) {\n\treturn file_teams_v1_teams_proto_rawDescGZIP(), []int{10}\n}", "func (*RefreshRuntimeTokenInternalRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_notebooks_v1_managed_service_proto_rawDescGZIP(), []int{12}\n}", "func (*WatchRequestTypeProto) Descriptor() ([]byte, []int) {\n\treturn file_raft_proto_rawDescGZIP(), []int{25}\n}", "func (*SwitchRuntimeRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_notebooks_v1_managed_service_proto_rawDescGZIP(), []int{7}\n}", "func (*SelectorVerificationReq) Descriptor() ([]byte, []int) {\n\treturn file_proto_selector_verification_msgs_proto_rawDescGZIP(), []int{0}\n}", "func (*TelemetryRequest) Descriptor() ([]byte, []int) {\n\treturn file_interservice_license_control_license_control_proto_rawDescGZIP(), []int{11}\n}", "func (*PatchModelVersionsRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{86}\n}", "func (*DeleteRequest) Descriptor() ([]byte, []int) {\n\treturn file_dictybase_api_jsonapi_request_proto_rawDescGZIP(), []int{7}\n}", "func (*ReadTensorboardUsageRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_aiplatform_v1_tensorboard_service_proto_rawDescGZIP(), []int{6}\n}", "func (*UpdateRuntimeRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_notebooks_v1_managed_service_proto_rawDescGZIP(), []int{11}\n}", "func (*CheckRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_api_servicecontrol_v1_service_controller_proto_rawDescGZIP(), []int{0}\n}", "func (*WatchProvisioningApprovalRequestRequest) Descriptor() ([]byte, []int) {\n\treturn edgelq_devices_proto_v1alpha_provisioning_approval_request_service_proto_rawDescGZIP(), []int{5}\n}", "func (*UpdateRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_task_v1_task_proto_rawDescGZIP(), []int{7}\n}", "func (*RefreshProjectRequest) Descriptor() ([]byte, []int) {\n\treturn file_web_proto_rawDescGZIP(), []int{2}\n}", "func (*RefreshTokenRequest) Descriptor() ([]byte, []int) {\n\treturn file_token_proto_rawDescGZIP(), []int{10}\n}", "func (*DeleteTasksRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{155}\n}", "func (*RevokeCertificateRequest) Descriptor() ([]byte, []int) {\n\treturn file_majordomo_proto_rawDescGZIP(), []int{18}\n}", "func (*UpdateRunRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_datacatalog_lineage_v1_lineage_proto_rawDescGZIP(), []int{13}\n}", "func (*AddPeerRequest) Descriptor() ([]byte, []int) {\n\treturn file_github_com_yahuizhan_dappley_metrics_go_api_rpc_pb_rpc_proto_rawDescGZIP(), []int{8}\n}", "func (*DeleteRequest) Descriptor() ([]byte, []int) {\n\treturn file_grpc_exercicio_proto_rawDescGZIP(), []int{7}\n}", "func (*MetricsServiceRequest) Descriptor() ([]byte, []int) {\n\treturn file_github_com_yahuizhan_dappley_metrics_go_api_rpc_pb_rpc_proto_rawDescGZIP(), []int{18}\n}", "func (*CreateIngressRuleRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_appengine_v1_appengine_proto_rawDescGZIP(), []int{24}\n}", "func (*DeleteRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_task_v1_task_proto_rawDescGZIP(), []int{13}\n}", "func (*ModelControlRequest) Descriptor() ([]byte, []int) {\n\treturn file_grpc_service_proto_rawDescGZIP(), []int{4}\n}", "func (*ChangeRequest) Descriptor() ([]byte, []int) {\n\treturn file_authorization_proto_rawDescGZIP(), []int{0}\n}", "func (*BatchUpdateReferencesRequest_Request) Descriptor() ([]byte, []int) {\n\treturn file_pkg_proto_icas_icas_proto_rawDescGZIP(), []int{1, 0}\n}", "func (*DeviceRestartRequest) Descriptor() ([]byte, []int) {\n\treturn file_api_worker_v1_device_state_proto_rawDescGZIP(), []int{0}\n}", "func (*TelemetryRequest) Descriptor() ([]byte, []int) {\n\treturn file_automate_gateway_api_telemetry_telemetry_proto_rawDescGZIP(), []int{0}\n}", "func (*UpgradeRuntimeRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_notebooks_v1_managed_service_proto_rawDescGZIP(), []int{9}\n}", "func (*RunOpsRes) Descriptor() ([]byte, []int) {\n\treturn file_api_ops_proto_rawDescGZIP(), []int{16}\n}", "func (*CodeLensRequest) Descriptor() ([]byte, []int) {\n\treturn file_protocol_rpc_rpc_proto_rawDescGZIP(), []int{163}\n}", "func (*DeleteProvisioningApprovalRequestRequest) Descriptor() ([]byte, []int) {\n\treturn edgelq_devices_proto_v1alpha_provisioning_approval_request_service_proto_rawDescGZIP(), []int{11}\n}", "func (*SendRequest) Descriptor() ([]byte, []int) {\n\treturn file_github_com_yahuizhan_dappley_metrics_go_api_rpc_pb_rpc_proto_rawDescGZIP(), []int{5}\n}", "func (*OutdatedRequest) Descriptor() ([]byte, []int) {\n\treturn file_cc_arduino_cli_commands_v1_commands_proto_rawDescGZIP(), []int{12}\n}", "func (*DeleteIngressRuleRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_appengine_v1_appengine_proto_rawDescGZIP(), []int{27}\n}", "func (*ComputeDoubleRequest) Descriptor() ([]byte, []int) {\n\treturn file_github_com_kubernetes_csi_csi_proxy_integrationtests_apigroups_api_dummy_v1_api_proto_rawDescGZIP(), []int{0}\n}", "func (*DeleteRuntimeRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_notebooks_v1_managed_service_proto_rawDescGZIP(), []int{4}\n}", "func (*UpdateIpPermissionRequest) Descriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_containerregistry_v1_registry_service_proto_rawDescGZIP(), []int{10}\n}", "func (*DeleteRunRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_datacatalog_lineage_v1_lineage_proto_rawDescGZIP(), []int{17}\n}", "func (*GetCollectorRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{163}\n}", "func (*UpdateWithdrawRequest) Descriptor() ([]byte, []int) {\n\treturn file_services_temporal_service_proto_rawDescGZIP(), []int{4}\n}", "func (*WatchRequest) Descriptor() ([]byte, []int) {\n\treturn file_authzed_api_v0_watch_service_proto_rawDescGZIP(), []int{0}\n}", "func (*SelectorVerificationsReq) Descriptor() ([]byte, []int) {\n\treturn file_proto_selector_verification_msgs_proto_rawDescGZIP(), []int{2}\n}", "func (*DescribePermissionRequest) Descriptor() ([]byte, []int) {\n\treturn file_pkg_role_pb_request_proto_rawDescGZIP(), []int{6}\n}", "func (*RefreshRequest) Descriptor() ([]byte, []int) {\n\treturn file_toit_api_auth_proto_rawDescGZIP(), []int{1}\n}", "func (*MemberTaskUpdateReq) Descriptor() ([]byte, []int) {\n\treturn file_ums_proto_rawDescGZIP(), []int{122}\n}", "func (*AddPermissionToRoleRequest) Descriptor() ([]byte, []int) {\n\treturn file_pkg_role_pb_request_proto_rawDescGZIP(), []int{7}\n}", "func (*UpdateTaskRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_task_task_proto_rawDescGZIP(), []int{6}\n}", "func (*ToggleWorkflowRequest) Descriptor() ([]byte, []int) {\n\treturn file_pkg_flow_grpc_workflows_proto_rawDescGZIP(), []int{35}\n}", "func (*MemberTaskDeleteReq) Descriptor() ([]byte, []int) {\n\treturn file_ums_proto_rawDescGZIP(), []int{124}\n}", "func (*CallRequest) Descriptor() ([]byte, []int) {\n\treturn file_ric_action_ricaction_proto_rawDescGZIP(), []int{0}\n}", "func (*DeleteRefRequest) Descriptor() ([]byte, []int) {\n\treturn file_go_chromium_org_luci_cipd_api_cipd_v1_repo_proto_rawDescGZIP(), []int{14}\n}" ]
[ "0.7107612", "0.7017801", "0.6950608", "0.67722416", "0.6765324", "0.6752489", "0.67259437", "0.67221236", "0.6707314", "0.67040014", "0.66941196", "0.6678439", "0.6670832", "0.6666073", "0.6662944", "0.66578716", "0.6657816", "0.66495866", "0.664471", "0.66404855", "0.6631255", "0.6597554", "0.65919924", "0.6584933", "0.65745836", "0.6569091", "0.6565999", "0.6565352", "0.6559366", "0.65591776", "0.65585953", "0.6558227", "0.6557893", "0.65558", "0.6550297", "0.654577", "0.65415055", "0.65385324", "0.653596", "0.653589", "0.6535817", "0.653425", "0.65275604", "0.6518443", "0.6518316", "0.651512", "0.6514705", "0.6513354", "0.6512329", "0.65121657", "0.6508914", "0.65031135", "0.65010965", "0.6498687", "0.6498653", "0.6498526", "0.64939034", "0.64910805", "0.6485894", "0.64841235", "0.6482553", "0.64769036", "0.64767355", "0.6470274", "0.64680564", "0.6467307", "0.6463596", "0.6463322", "0.6462947", "0.6461622", "0.64614546", "0.6460204", "0.64568454", "0.6448052", "0.6444464", "0.6444144", "0.64426154", "0.6441573", "0.64397013", "0.6438975", "0.6438892", "0.6437562", "0.643587", "0.6435127", "0.6432306", "0.64272976", "0.6426354", "0.6425325", "0.6424801", "0.6422673", "0.64224243", "0.6421865", "0.6418393", "0.6417701", "0.64172196", "0.6416531", "0.64149666", "0.6414966", "0.6412226", "0.6410903" ]
0.7500174
0
Deprecated: Use RunOpsRes.ProtoReflect.Descriptor instead.
Устарело: используйте RunOpsRes.ProtoReflect.Descriptor вместо этого.
func (*RunOpsRes) Descriptor() ([]byte, []int) { return file_api_ops_proto_rawDescGZIP(), []int{16} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (*RunOpsReq) Descriptor() ([]byte, []int) {\n\treturn file_api_ops_proto_rawDescGZIP(), []int{15}\n}", "func (*UpdateTensorboardRunRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_aiplatform_v1_tensorboard_service_proto_rawDescGZIP(), []int{24}\n}", "func (*GetTensorboardRunRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_aiplatform_v1_tensorboard_service_proto_rawDescGZIP(), []int{19}\n}", "func (*PatchCollectorsRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{161}\n}", "func (*DiagOperation) Descriptor() ([]byte, []int) {\n\treturn file_testvector_tv_proto_rawDescGZIP(), []int{10}\n}", "func (StandardPTransforms_DeprecatedPrimitives) EnumDescriptor() ([]byte, []int) {\n\treturn file_org_apache_beam_model_pipeline_v1_beam_runner_api_proto_rawDescGZIP(), []int{4, 1}\n}", "func (*Run) Descriptor() ([]byte, []int) {\n\treturn file_external_cfgmgmt_response_nodes_proto_rawDescGZIP(), []int{2}\n}", "func (*DeleteTensorboardRunRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_aiplatform_v1_tensorboard_service_proto_rawDescGZIP(), []int{25}\n}", "func (*StandardProtocols) Descriptor() ([]byte, []int) {\n\treturn file_org_apache_beam_model_pipeline_v1_beam_runner_api_proto_rawDescGZIP(), []int{54}\n}", "func (*Deprecation) Descriptor() ([]byte, []int) {\n\treturn file_external_cfgmgmt_response_nodes_proto_rawDescGZIP(), []int{8}\n}", "func (*StandardRunnerProtocols) Descriptor() ([]byte, []int) {\n\treturn file_org_apache_beam_model_pipeline_v1_beam_runner_api_proto_rawDescGZIP(), []int{55}\n}", "func (*CreateTensorboardRunRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_aiplatform_v1_tensorboard_service_proto_rawDescGZIP(), []int{18}\n}", "func (*QueryPlanStatusResponseProto) Descriptor() ([]byte, []int) {\n\treturn file_ClientDatanodeProtocol_proto_rawDescGZIP(), []int{25}\n}", "func (*CancelPlanResponseProto) Descriptor() ([]byte, []int) {\n\treturn file_ClientDatanodeProtocol_proto_rawDescGZIP(), []int{23}\n}", "func (*Operation) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_sql_v1beta4_cloud_sql_resources_proto_rawDescGZIP(), []int{47}\n}", "func (*PatchTasksRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{154}\n}", "func (*PlanChange_Removed) Descriptor() ([]byte, []int) {\n\treturn edgelq_limits_proto_v1alpha2_plan_change_proto_rawDescGZIP(), []int{0, 3}\n}", "func (*Operation) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_sql_v1_cloud_sql_resources_proto_rawDescGZIP(), []int{24}\n}", "func (*Module) Descriptor() ([]byte, []int) {\n\treturn file_google_devtools_cloudtrace_v2_trace_proto_rawDescGZIP(), []int{3}\n}", "func (*UpdateTensorboardOperationMetadata) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_aiplatform_v1_tensorboard_service_proto_rawDescGZIP(), []int{45}\n}", "func (StandardRunnerProtocols_Enum) EnumDescriptor() ([]byte, []int) {\n\treturn file_org_apache_beam_model_pipeline_v1_beam_runner_api_proto_rawDescGZIP(), []int{55, 0}\n}", "func (*SelectorVerificationRes) Descriptor() ([]byte, []int) {\n\treturn file_proto_selector_verification_msgs_proto_rawDescGZIP(), []int{1}\n}", "func (*AnalysisMessageWeakSchema_ArgType) Descriptor() ([]byte, []int) {\n\treturn file_analysis_v1alpha1_message_proto_rawDescGZIP(), []int{1, 0}\n}", "func (*ManagementOperation) Descriptor() ([]byte, []int) {\n\treturn file_testvector_tv_proto_rawDescGZIP(), []int{13}\n}", "func (*ApiWarning) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_sql_v1_cloud_sql_resources_proto_rawDescGZIP(), []int{1}\n}", "func (*WinRMListener) Descriptor() ([]byte, []int) {\n\treturn file_moc_common_computecommon_proto_rawDescGZIP(), []int{0}\n}", "func (*RunWorkflowRequest) Descriptor() ([]byte, []int) {\n\treturn file_pkg_flow_grpc_instances_proto_rawDescGZIP(), []int{15}\n}", "func (*VirtualMachineRunCommandInstanceView) Descriptor() ([]byte, []int) {\n\treturn file_moc_common_computecommon_proto_rawDescGZIP(), []int{6}\n}", "func (*RefreshRequest) Descriptor() ([]byte, []int) {\n\treturn file_cloudprovider_externalgrpc_protos_externalgrpc_proto_rawDescGZIP(), []int{16}\n}", "func (*DeleteCollectorsRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{162}\n}", "func (*Resource) Descriptor() ([]byte, []int) {\n\treturn file_apiextensions_fn_proto_v1beta1_run_function_proto_rawDescGZIP(), []int{5}\n}", "func (*RefreshCallQueueResponseProto) Descriptor() ([]byte, []int) {\n\treturn file_RefreshCallQueueProtocol_proto_rawDescGZIP(), []int{1}\n}", "func (*LabelledPayload) Descriptor() ([]byte, []int) {\n\treturn file_org_apache_beam_model_pipeline_v1_beam_runner_api_proto_rawDescGZIP(), []int{59}\n}", "func (*Preferences) Descriptor() ([]byte, []int) {\n\treturn file_google_ads_googleads_v2_services_reach_plan_service_proto_rawDescGZIP(), []int{8}\n}", "func (*SecurityOperation) Descriptor() ([]byte, []int) {\n\treturn file_testvector_tv_proto_rawDescGZIP(), []int{9}\n}", "func (*GetTensorboardRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_aiplatform_v1_tensorboard_service_proto_rawDescGZIP(), []int{1}\n}", "func (*PlanChange) Descriptor() ([]byte, []int) {\n\treturn edgelq_limits_proto_v1alpha2_plan_change_proto_rawDescGZIP(), []int{0}\n}", "func (*ReadTensorboardUsageRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_aiplatform_v1_tensorboard_service_proto_rawDescGZIP(), []int{6}\n}", "func (*GenerateProductMixIdeasRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_ads_googleads_v2_services_reach_plan_service_proto_rawDescGZIP(), []int{7}\n}", "func (*ApiWarning) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_sql_v1beta4_cloud_sql_resources_proto_rawDescGZIP(), []int{1}\n}", "func (*RawOp) Descriptor() ([]byte, []int) {\n\treturn file_go_chromium_org_luci_server_quota_quotapb_update_accounts_proto_rawDescGZIP(), []int{1}\n}", "func (*UpdateTensorboardRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_aiplatform_v1_tensorboard_service_proto_rawDescGZIP(), []int{4}\n}", "func (*DeleteRunRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_datacatalog_lineage_v1_lineage_proto_rawDescGZIP(), []int{17}\n}", "func (*PlanChange_Modified) Descriptor() ([]byte, []int) {\n\treturn edgelq_limits_proto_v1alpha2_plan_change_proto_rawDescGZIP(), []int{0, 1}\n}", "func (*WriteTensorboardRunDataResponse) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_aiplatform_v1_tensorboard_service_proto_rawDescGZIP(), []int{41}\n}", "func (*ExternalPayload) Descriptor() ([]byte, []int) {\n\treturn file_org_apache_beam_model_pipeline_v1_beam_runner_api_proto_rawDescGZIP(), []int{53}\n}", "func (x *fastReflection_ServiceCommandDescriptor) Descriptor() protoreflect.MessageDescriptor {\n\treturn md_ServiceCommandDescriptor\n}", "func (*FetchInstancesInstruction) Descriptor() ([]byte, []int) {\n\treturn file_proto_api_proto_rawDescGZIP(), []int{10}\n}", "func (StandardProtocols_Enum) EnumDescriptor() ([]byte, []int) {\n\treturn file_org_apache_beam_model_pipeline_v1_beam_runner_api_proto_rawDescGZIP(), []int{54, 0}\n}", "func (*GetDelegationTokenResponseProto) Descriptor() ([]byte, []int) {\n\treturn file_Security_proto_rawDescGZIP(), []int{4}\n}", "func (*RevokeTokensRequest) Descriptor() ([]byte, []int) {\n\treturn file_token_proto_rawDescGZIP(), []int{17}\n}", "func (*StandardResourceHints) Descriptor() ([]byte, []int) {\n\treturn file_org_apache_beam_model_pipeline_v1_beam_runner_api_proto_rawDescGZIP(), []int{63}\n}", "func (*ValidateReply) Descriptor() ([]byte, []int) {\n\treturn file_protobuf_clusrun_proto_rawDescGZIP(), []int{18}\n}", "func (*StandardCoders) Descriptor() ([]byte, []int) {\n\treturn file_org_apache_beam_model_pipeline_v1_beam_runner_api_proto_rawDescGZIP(), []int{29}\n}", "func (*CodeLens) Descriptor() ([]byte, []int) {\n\treturn file_protocol_rpc_rpc_proto_rawDescGZIP(), []int{164}\n}", "func (*Decl) Descriptor() ([]byte, []int) {\n\treturn file_google_api_expr_v1alpha1_checked_proto_rawDescGZIP(), []int{2}\n}", "func (*ScanRunWarningTrace) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_websecurityscanner_v1_scan_run_warning_trace_proto_rawDescGZIP(), []int{0}\n}", "func (*GetRunRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_datacatalog_lineage_v1_lineage_proto_rawDescGZIP(), []int{14}\n}", "func (*BatchCreateTensorboardRunsRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_aiplatform_v1_tensorboard_service_proto_rawDescGZIP(), []int{16}\n}", "func (*ReadTensorboardUsageResponse) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_aiplatform_v1_tensorboard_service_proto_rawDescGZIP(), []int{7}\n}", "func (StandardResourceHints_Enum) EnumDescriptor() ([]byte, []int) {\n\treturn file_org_apache_beam_model_pipeline_v1_beam_runner_api_proto_rawDescGZIP(), []int{63, 0}\n}", "func (*Diagnostic) Descriptor() ([]byte, []int) {\n\treturn file_google_api_servicemanagement_v1_resources_proto_rawDescGZIP(), []int{2}\n}", "func (*TaskRun) Descriptor() ([]byte, []int) {\n\treturn file_taskrun_proto_rawDescGZIP(), []int{0}\n}", "func (*PatchAnnotationsRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{4}\n}", "func (*ClrThread) Descriptor() ([]byte, []int) {\n\treturn file_language_agent_CLRMetric_proto_rawDescGZIP(), []int{3}\n}", "func (*TelemetryParams) Descriptor() ([]byte, []int) {\n\treturn file_protocol_rpc_rpc_proto_rawDescGZIP(), []int{62}\n}", "func (*CLRMetric) Descriptor() ([]byte, []int) {\n\treturn file_language_agent_CLRMetric_proto_rawDescGZIP(), []int{1}\n}", "func (*Calculator) Descriptor() ([]byte, []int) {\n\treturn file_basicpb_unary_api_proto_rawDescGZIP(), []int{1}\n}", "func (*RefreshProjectRequest) Descriptor() ([]byte, []int) {\n\treturn file_web_proto_rawDescGZIP(), []int{2}\n}", "func (x *fastReflection_FlagOptions) Descriptor() protoreflect.MessageDescriptor {\n\treturn md_FlagOptions\n}", "func (*RefreshNamenodesResponseProto) Descriptor() ([]byte, []int) {\n\treturn file_ClientDatanodeProtocol_proto_rawDescGZIP(), []int{3}\n}", "func (*RefreshRuntimeTokenInternalRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_notebooks_v1_managed_service_proto_rawDescGZIP(), []int{12}\n}", "func (*DiagnoseRuntimeRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_notebooks_v1_managed_service_proto_rawDescGZIP(), []int{14}\n}", "func (*RevokeJobRequest) Descriptor() ([]byte, []int) {\n\treturn file_pkg_noderpc_proto_feeds_manager_proto_rawDescGZIP(), []int{20}\n}", "func (*Ref) Descriptor() ([]byte, []int) {\n\treturn file_pkg_flow_grpc_workflows_proto_rawDescGZIP(), []int{15}\n}", "func (*Refresh) Descriptor() ([]byte, []int) {\n\treturn file_uni_proto_rawDescGZIP(), []int{12}\n}", "func (*Trigger) Descriptor() ([]byte, []int) {\n\treturn file_org_apache_beam_model_pipeline_v1_beam_runner_api_proto_rawDescGZIP(), []int{37}\n}", "func (*ControlPlaneOperation) Descriptor() ([]byte, []int) {\n\treturn file_testvector_tv_proto_rawDescGZIP(), []int{0}\n}", "func (*SemanticTokensEdit) Descriptor() ([]byte, []int) {\n\treturn file_protocol_rpc_rpc_proto_rawDescGZIP(), []int{224}\n}", "func (*RanfunctionName) Descriptor() ([]byte, []int) {\n\treturn file_e2sm_mho_go_v2_e2sm_v2_proto_rawDescGZIP(), []int{19}\n}", "func (StatusMessage_Reference) EnumDescriptor() ([]byte, []int) {\n\treturn file_google_devtools_clouddebugger_v2_data_proto_rawDescGZIP(), []int{1, 0}\n}", "func (*Reference) Descriptor() ([]byte, []int) {\n\treturn file_google_api_expr_v1alpha1_checked_proto_rawDescGZIP(), []int{3}\n}", "func (*RenewDelegationTokenResponseProto) Descriptor() ([]byte, []int) {\n\treturn file_Security_proto_rawDescGZIP(), []int{6}\n}", "func (*TraceProto) Descriptor() ([]byte, []int) {\n\treturn file_internal_tracing_extended_extended_trace_proto_rawDescGZIP(), []int{0}\n}", "func (*SemanticTokensLegend) Descriptor() ([]byte, []int) {\n\treturn file_protocol_rpc_rpc_proto_rawDescGZIP(), []int{215}\n}", "func (*Description) Descriptor() ([]byte, []int) {\n\treturn file_external_cfgmgmt_response_nodes_proto_rawDescGZIP(), []int{7}\n}", "func (*CancelDelegationTokenResponseProto) Descriptor() ([]byte, []int) {\n\treturn file_Security_proto_rawDescGZIP(), []int{8}\n}", "func (*SelectorVerificationsRes) Descriptor() ([]byte, []int) {\n\treturn file_proto_selector_verification_msgs_proto_rawDescGZIP(), []int{3}\n}", "func (*CreateTensorboardOperationMetadata) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_aiplatform_v1_tensorboard_service_proto_rawDescGZIP(), []int{44}\n}", "func (*UpdateRunRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_datacatalog_lineage_v1_lineage_proto_rawDescGZIP(), []int{13}\n}", "func (*UpdateDeleteDisconnectedServicesConfigRes) Descriptor() ([]byte, []int) {\n\treturn file_external_applications_applications_proto_rawDescGZIP(), []int{18}\n}", "func (*Run) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_datacatalog_lineage_v1_lineage_proto_rawDescGZIP(), []int{1}\n}", "func (*RestartServicesRequest) Descriptor() ([]byte, []int) {\n\treturn file_orc8r_protos_magmad_proto_rawDescGZIP(), []int{9}\n}", "func (*WriteTensorboardRunDataRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_aiplatform_v1_tensorboard_service_proto_rawDescGZIP(), []int{40}\n}", "func (*PCollection) Descriptor() ([]byte, []int) {\n\treturn file_org_apache_beam_model_pipeline_v1_beam_runner_api_proto_rawDescGZIP(), []int{7}\n}", "func (*RunList) Descriptor() ([]byte, []int) {\n\treturn file_external_cfgmgmt_response_nodes_proto_rawDescGZIP(), []int{6}\n}", "func (*DelegateAction) Descriptor() ([]byte, []int) {\n\treturn file_github_com_solo_io_gloo_projects_gateway_api_v1_virtual_service_proto_rawDescGZIP(), []int{4}\n}", "func (*Performance) Descriptor() ([]byte, []int) {\n\treturn file_commissionService_proto_rawDescGZIP(), []int{2}\n}", "func (*ObjectDetectionModule) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_visualinspection_v1beta1_module_proto_rawDescGZIP(), []int{4}\n}", "func (*ListTensorboardRunsRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_aiplatform_v1_tensorboard_service_proto_rawDescGZIP(), []int{22}\n}" ]
[ "0.6750467", "0.67362535", "0.6681629", "0.66724443", "0.66413933", "0.66265243", "0.6616651", "0.6573871", "0.65253603", "0.6516421", "0.65161854", "0.65145516", "0.650977", "0.64996266", "0.6403638", "0.63801986", "0.6372133", "0.6363645", "0.6316747", "0.6310355", "0.6304522", "0.6289984", "0.6289342", "0.62787557", "0.6278432", "0.6276873", "0.62725", "0.62704253", "0.6265809", "0.6263561", "0.6263043", "0.6260642", "0.6259503", "0.6257157", "0.62363905", "0.62362856", "0.62358344", "0.62293947", "0.6223681", "0.6222004", "0.6218962", "0.6211486", "0.6209614", "0.62081665", "0.62047577", "0.6203609", "0.6201658", "0.62005013", "0.6194407", "0.6192818", "0.61918736", "0.61890703", "0.6187289", "0.61862403", "0.6183751", "0.6183291", "0.6181008", "0.6173144", "0.6169328", "0.6168803", "0.6166364", "0.616426", "0.6160231", "0.6159235", "0.6156902", "0.61496794", "0.6147749", "0.6145528", "0.6144662", "0.61442465", "0.61422265", "0.6138133", "0.6137813", "0.61350626", "0.6130417", "0.6126522", "0.6126184", "0.61226404", "0.6122347", "0.6122278", "0.6122147", "0.6120917", "0.61201096", "0.6117437", "0.6112753", "0.6110256", "0.61093867", "0.6106151", "0.61036384", "0.61028385", "0.610241", "0.6098005", "0.6097212", "0.6096685", "0.609617", "0.6095411", "0.6094804", "0.60941374", "0.6093977", "0.6093747" ]
0.70218784
0
TryUnlock closes and removes the lockfile
TryUnlock закрывает и удаляет файл с замком
func (s *Single) TryUnlock() error { if err := s.file.Close(); err != nil { return fmt.Errorf("failed to close the lock file: %v", err) } if err := os.Remove(s.Filename()); err != nil { return fmt.Errorf("failed to remove the lock file: %v", err) } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (l *lock) Unlock() error {\n\treturn l.file.Close()\n}", "func (l *NullPathLocker) Unlock() {}", "func release() error {\n\tif disabled() {\n\t\treturn nil\n\t}\n\n\tpath, err := path(lockFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn os.Remove(path)\n}", "func (l *Lock) Unlock() (err error) {\n\t_, err = fs.Stat(l.name)\n\tif err != nil {\n\t\terr = nil\n\t\treturn\n\t}\n\terr = fs.Remove(l.name)\n\treturn\n}", "func (lf *LockFile) Unlock() error {\n\n\tlog.Printf(\"Deleting lockfile at this key '%s'\", lf.Path)\n\n\tif lf.ConsulAddress == \"\" {\n\t\t// Delete the file\n\t\terr := os.Remove(lf.Path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tlf.locked = false\n\t\treturn nil\n\t}\n\n\t// Delete the KV pair\n\terr := DeleteValueFromConsul(lf.ConsulAddress, lf.Path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlf.locked = false\n\treturn nil\n}", "func (f *file) Unlock() error {\n\treturn nil\n}", "func (f *FileLock) Unlock() error {\n\terr := f.fileH.Close()\n\tf.fileH = nil\n\treturn err\n}", "func (f *FLock) Unlock() error {\n\tf.locker.Lock()\n\tdefer f.locker.Unlock()\n\n\tif err := syscall.Flock(int(f.lockedFile.Fd()), syscall.LOCK_UN); err != nil {\n\t\treturn err\n\t}\n\n\treturn f.closeLockedFile()\n}", "func (l *FileLock) Unlock() error {\n\tif l.fd == nil {\n\t\treturn fmt.Errorf(\"file %s descriptor is nil\", l.fileName)\n\t}\n\tfd := l.fd\n\tl.fd = nil\n\n\tdefer fd.Close()\n\tif err := syscall.Flock(int(fd.Fd()), syscall.LOCK_UN); err != nil {\n\t\treturn errors.Wrapf(err, \"file %s unlock failed\", l.fileName)\n\t}\n\treturn nil\n}", "func (l *FileLock) Unlock() error {\n\treturn syscall.Flock(l.fd, syscall.LOCK_UN)\n}", "func TestLockAndUnlock(t *testing.T) {\n\tf, err := ioutil.TempFile(\"\", \"lock\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tf.Close()\n\tdefer func() {\n\t\terr = os.Remove(f.Name())\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}()\n\n\t// lock the file\n\tl, err := LockedOpenFile(f.Name(), os.O_WRONLY, 0600)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// unlock the file\n\tif err = l.Close(); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// try lock the unlocked file\n\tdupl, err := LockedOpenFile(f.Name(), os.O_WRONLY|os.O_CREATE, 0600)\n\tif err != nil {\n\t\tt.Errorf(\"err = %v, want %v\", err, nil)\n\t}\n\n\t// blocking on locked file\n\tlocked := make(chan struct{}, 1)\n\tgo func() {\n\t\tbl, blerr := LockedOpenFile(f.Name(), os.O_WRONLY, 0600)\n\t\tif blerr != nil {\n\t\t\tt.Error(blerr)\n\t\t\treturn\n\t\t}\n\t\tlocked <- struct{}{}\n\t\tif blerr = bl.Close(); blerr != nil {\n\t\t\tt.Error(blerr)\n\t\t\treturn\n\t\t}\n\t}()\n\n\tselect {\n\tcase <-locked:\n\t\tt.Error(\"unexpected unblocking\")\n\tcase <-time.After(100 * time.Millisecond):\n\t}\n\n\t// unlock\n\tif err = dupl.Close(); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// the previously blocked routine should be unblocked\n\tselect {\n\tcase <-locked:\n\tcase <-time.After(1 * time.Second):\n\t\tt.Error(\"unexpected blocking\")\n\t}\n}", "func (f *File) Unlock() error {\n\treturn nil\n}", "func (l *FileLock) Close() error {\n\tfd := l.fd\n\tl.fd = -1\n\treturn syscall.Close(fd)\n}", "func Unlock() {\n\tlock.Unlock()\n}", "func (f *Flock) Unlock() error {\n\tf.m.Lock()\n\tdefer f.m.Unlock()\n\n\t// if we aren't locked or if the lockfile instance is nil\n\t// just return a nil error because we are unlocked\n\tif (!f.l && !f.r) || f.fh == nil {\n\t\treturn nil\n\t}\n\n\t// mark the file as unlocked\n\tif _, errNo := unlockFileEx(syscall.Handle(f.fh.Fd()), 0, 1, 0, &syscall.Overlapped{}); errNo > 0 {\n\t\treturn errNo\n\t}\n\n\tf.fh.Close()\n\n\tf.l = false\n\tf.r = false\n\tf.fh = nil\n\n\treturn nil\n}", "func (f *FileLock) Unlock() {\n\tif f.is_locked {\n\t\tf.f_lock.Unlock()\n\t}\n}", "func (il *internalLocker) Unlock(ctx context.Context) error {\n\tif err := il.mu.Unlock(ctx); err != nil {\n\t\tlog.Logger.Error(err)\n\t\treturn err\n\t}\n\n\treturn il.session.Close()\n}", "func (f *File) Unlock() error {\n\tif err := syscall.Flock(f.lockfd, syscall.LOCK_UN); err != nil {\n\t\treturn err\n\t}\n\tf.mu.Unlock()\n\treturn nil\n}", "func (s *Snapshot) closeLocked() error {\n\ts.db.mu.snapshots.remove(s)\n\n\t// If s was the previous earliest snapshot, we might be able to reclaim\n\t// disk space by dropping obsolete records that were pinned by s.\n\tif e := s.db.mu.snapshots.earliest(); e > s.seqNum {\n\t\ts.db.maybeScheduleCompactionPicker(pickElisionOnly)\n\t}\n\ts.db = nil\n\treturn nil\n}", "func Unlock() {\n\tmutex.Unlock()\n}", "func unlock(lock *flock.Flock) {\n\terr := lock.Unlock()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func (m *MutexSafe) unlock() {\n\tm.Mutex.Unlock()\n}", "func TestGetLock(t *testing.T) {\n\tlockfile := lockOrFail(t)\n\tdefer removeTestLock(lockfile)\n}", "func (f *Flock) Close() error {\n\treturn f.Unlock()\n}", "func (l *Locker) Unlock() {\n\tif l.locker != -1 {\n\t\tpanic(\"db: Unlock of unlocked Locker\")\n\t}\n\tatomic.StoreInt32(&l.locker, 0)\n}", "func Release(lock int) error {\n\treturn unix.Flock(lock, unix.LOCK_UN)\n}", "func Release(fd int) error {\n\tdefer unix.Close(fd)\n\tif err := unix.Flock(fd, unix.LOCK_UN); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (l *fileLock) tryLock() (Unlocker, error) {\n\tl.mu.Lock()\n\terr := syscall.Flock(l.fd, syscall.LOCK_EX|syscall.LOCK_NB)\n\tswitch err {\n\tcase syscall.EWOULDBLOCK:\n\t\tl.mu.Unlock()\n\t\treturn nopUnlocker{}, nil\n\tcase nil:\n\t\treturn l, nil\n\tdefault:\n\t\tl.mu.Unlock()\n\t\treturn nil, err\n\t}\n}", "func (l *FileLocker) Release() {\n\tl.f.Close()\n}", "func (file *LockFile) Unlock() error {\n\treturn unlockFile(file.Fd())\n}", "func (l *etcdLock) Unlock() {\n\tif l.cancel != nil {\n\t\tl.cancel()\n\t}\n}", "func (li *localLockInstance) Unlock() {\n\treadLock := false\n\tli.ns.unlock(li.volume, li.path, li.opsID, readLock)\n}", "func (mfs *MinFS) Unlock(path string) error {\n\tmfs.m.Lock()\n\tdefer mfs.m.Unlock()\n\n\tdelete(mfs.locks, path)\n\n\treturn nil\n}", "func (f *volatileFile) Unlock(lock C.int) C.int {\n\tf.mu.Lock()\n\tdefer f.mu.Unlock()\n\n\tswitch lock {\n\tcase C.SQLITE_LOCK_NONE:\n\t\tf.none--\n\tcase C.SQLITE_LOCK_SHARED:\n\t\tf.shared--\n\tcase C.SQLITE_LOCK_RESERVED:\n\t\tf.reserved--\n\tcase C.SQLITE_LOCK_PENDING:\n\t\tf.pending--\n\tcase C.SQLITE_LOCK_EXCLUSIVE:\n\t\tf.exclusive--\n\tdefault:\n\t\treturn C.SQLITE_ERROR\n\t}\n\n\treturn C.SQLITE_OK\n}", "func (w *Writer) unlock() {\n\tw.mutex.Unlock()\n}", "func Unlock() {\n\t// TO DO\n}", "func (di *distLockInstance) Unlock() {\n\tdi.rwMutex.Unlock()\n}", "func (g *glock) Unlock() {\n\tdefer func() {\n\t\t// Cancel the context when this returns\n\t\tif g.cancel != nil {\n\t\t\tg.cancel()\n\t\t\tg.cancel = nil\n\t\t}\n\t}()\n\tif !g.locked {\n\t\t// Called Unlock without actually having the lock,\n\t\t// do nothing or risk overriding someone else's lock\n\t\treturn\n\t}\n\tdefer g.mt.Unlock()\n\tg.waiting = false\n\n\tfor {\n\t\t// ensure the lock is ours\n\t\tkv, err := g.gok.Get(context.Background(), g.key)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Sanity check, that the lock is ours\n\t\tif string(kv.Value) != \"locked_\"+g.processID {\n\t\t\treturn\n\t\t}\n\n\t\terr = g.gok.Set(context.Background(), g.key, []byte(\"unlocked\"))\n\t\tif err == nil {\n\t\t\tg.locked = false\n\t\t\treturn\n\t\t}\n\t}\n}", "func (m *neighborEntryRWMutex) Unlock() {\n\tm.mu.Unlock()\n\tlocking.DelGLock(neighborEntryprefixIndex, -1)\n}", "func (s *SharedState) unlock() {\n s.mutex.Unlock()\n}", "func (rs *RedisService) Unlock(lock storages.Lock) error {\n\tlock.Unlock()\n\n\trs.selfmutex.Lock()\n\tdelete(rs.unlockMe, lock.Identifier())\n\trs.selfmutex.Unlock()\n\n\treturn nil\n}", "func (m *RWMutex) Unlock() {\n\tm.mu.Unlock()\n\tlocking.DelGLock(genericMarkIndex, -1)\n}", "func (l *fileSink) closeFileLocked() error {\n\tif l.mu.file == nil {\n\t\treturn nil\n\t}\n\n\t// First disconnect stderr, if it was connected. We do this before\n\t// closing the file to ensure no direct stderr writes are lost.\n\tif err := l.maybeRelinquishInternalStderrLocked(); err != nil {\n\t\treturn err\n\t}\n\n\tif sb, ok := l.mu.file.(*syncBuffer); ok {\n\t\tif err := sb.file.Close(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tl.mu.file = nil\n\n\treturn nil\n}", "func (sm *SourceMgr) Release() {\n\tsm.lf.Close()\n\tos.Remove(filepath.Join(sm.cachedir, \"sm.lock\"))\n}", "func (n *nsLockMap) ForceUnlock(volume, path string) {\n\tn.lockMapMutex.Lock()\n\tdefer n.lockMapMutex.Unlock()\n\n\t// Clarification on operation:\n\t// - In case of FS or XL we call ForceUnlock on the local globalNSMutex\n\t// (since there is only a single server) which will cause the 'stuck'\n\t// mutex to be removed from the map. Existing operations for this\n\t// will continue to be blocked (and timeout). New operations on this\n\t// resource will use a new mutex and proceed normally.\n\t//\n\t// - In case of Distributed setup (using dsync), there is no need to call\n\t// ForceUnlock on the server where the lock was acquired and is presumably\n\t// 'stuck'. Instead dsync.ForceUnlock() will release the underlying locks\n\t// that participated in granting the lock. Any pending dsync locks that\n\t// are blocking can now proceed as normal and any new locks will also\n\t// participate normally.\n\tif n.isDistXL { // For distributed mode, broadcast ForceUnlock message.\n\t\tdsync.NewDRWMutex(context.Background(), pathJoin(volume, path), globalDsync).ForceUnlock()\n\t}\n\n\t// Remove lock from the map.\n\tdelete(n.lockMap, nsParam{volume, path})\n}", "func (l *lock) TryLock() error {\n\terr := os.Chmod(l.fname, syscall.DMEXCL|0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf, err := os.Open(l.fname)\n\tif err != nil {\n\t\treturn ErrLocked\n\t}\n\n\tl.file = f\n\treturn nil\n}", "func UnlockConfig() {\n\tif lockFilePath != \"\" {\n\t\terr := os.Remove(lockFilePath)\n\t\tif err != nil {\n\t\t\tlogging.Error(\"config\", \"Failed to delete lockfile: \"+err.Error())\n\t\t}\n\t}\n}", "func (sm *SourceMgr) Release() {\n\tos.Remove(path.Join(sm.cachedir, \"sm.lock\"))\n}", "func (aio *AsyncIO) FUnlock() error {\n\treturn nil\n}", "func (d *Dam) Unlock() {\n\td.freeze.Unlock()\n}", "func (m *Mutex) Release(lock *Lock) error {\n\tfm := lock.Data.(*filemutex.FileMutex)\n\tlfn := LockFileName(lock.Name)\n\treturn internalRelease(fm, lfn, m.Logger)\n}", "func Unlock(ctx context.Context, lockContext, lockID string) {\n\tgetLock(ctx, lockID).Unlock()\n\tLogc(ctx).WithField(\"lock\", lockID).Debugf(\"Released shared lock (%s).\", lockContext)\n}", "func (lm *LMutex) Unlock() {\n\tif !atomic.CompareAndSwapInt64(&lm.state, WRITELOCK, NOLOCKS) {\n\t\tpanic(\"Trying to Unlock() while no Lock() is active\")\n\t}\n}", "func (this *Lock) Release() error {\n\tres, err := this.manager.GetClient().Get(this.name).Result()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif this.value != res {\n\t\treturn ERR_NOT_MINE_LOCK\n\t}\n\terr = this.manager.GetClient().Watch(func(tx *redis.Tx) error {\n\t\tres, err := tx.Del(this.name).Result()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif res == 0 {\n\t\t\treturn ERR_NOT_MINE_LOCK\n\t\t}\n\t\treturn nil\n\t}, this.name)\n\n\treturn err\n}", "func (el *Lock) Unlock() error {\n\treturn el.Delete(el.key())\n}", "func (u unlocker) Unlock() error {\n\tkvp, meta, err := u.session.client.KV().Get(u.key, nil)\n\tif err != nil {\n\t\treturn NewKVError(\"get\", u.key, err)\n\t}\n\tif kvp == nil {\n\t\treturn nil\n\t}\n\tif kvp.Session != u.session.session {\n\t\treturn AlreadyLockedError{Key: u.key}\n\t}\n\n\tsuccess, _, err := u.session.client.KV().DeleteCAS(&api.KVPair{\n\t\tKey: u.key,\n\t\tModifyIndex: meta.LastIndex,\n\t}, nil)\n\tif err != nil {\n\t\treturn NewKVError(\"deletecas\", u.key, err)\n\t}\n\tif !success {\n\t\t// the key has been mutated since we checked it - probably someone\n\t\t// overrode our lock on it or deleted it themselves\n\t\treturn AlreadyLockedError{Key: u.key}\n\t}\n\treturn nil\n}", "func (l *Lock) Unlock(ctx context.Context) error {\n\tl.mu.Lock()\n\tdefer l.mu.Unlock()\n\n\tconn, err := l.Pool.GetContext(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer conn.Close()\n\tif l.token == nil {\n\t\tl.token = randomToken()\n\t}\n\n\treply, err := redis.Int(unlockScript.Do(conn, l.Key, l.token))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif reply != 1 {\n\t\treturn ErrNotHeld\n\t}\n\tl.token = nil\n\treturn nil\n}", "func (service LockService) Unlock(group *scaley.Group) error {\n\tif service.Locked(group) {\n\t\terr := Root.Remove(lockfile(group))\n\t\tif err != nil {\n\t\t\treturn scaley.UnlockFailure{Group: group}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (r *RedisDL) Unlock() error {\n\tr.m.Lock()\n\tdefer r.m.Unlock()\n\treturn r.deleteToken()\n}", "func (w *wrapper) Release(path string, fd uint64) int {\n\tw.fdMtx.Lock()\n\tdefer w.fdMtx.Unlock()\n\tfh, ok := w.fileDescriptors[fd]\n\tif !ok {\n\t\treturn -fuse.EINVAL\n\t}\n\tdelete(w.fileDescriptors, fd)\n\t// It's fine if the write lock is still being held. The Close will soon unblock that.\n\tdelete(w.writeLocks, fd)\n\treturn convertError(fh.Close())\n}", "func (self *Map) unlock() {\n\tif self.atomic != nil {\n\t\tself.atomic.Unlock()\n\t}\n}", "func (c *crdLock) Unlock(ctx context.Context) error {\n\treturn nil\n}", "func (e *Enumerate) unlock() {\n\te.u.m.Unlock()\n}", "func (s *Single) CheckLock() error {\n\n\tif err := os.Remove(s.Filename()); err != nil && !os.IsNotExist(err) {\n\t\treturn ErrAlreadyRunning\n\t}\n\n\tfile, err := os.OpenFile(s.Filename(), os.O_EXCL|os.O_CREATE, 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.file = file\n\n\treturn nil\n}", "func (lock *ALock) Unlock() {\n\tslot := atomic.LoadInt32(&lock.slot)\n\tlock.Flags[(slot+1)%lock.nThreads] = true\n}", "func (self *Conn) Unlock() {\n\tif self.mainloop != nil && self.isLocked {\n\t\tC.pa_threaded_mainloop_unlock(self.mainloop)\n\t\tself.isLocked = false\n\t}\n}", "func (bl *OnceBlastLock) Close() {\n\tclose(bl.close)\n}", "func (rw *RWMutex) Unlock() {\n\tatomic.StoreInt32(&rw.wLocked, 0)\n\trw.RWMutex.Unlock()\n}", "func TestLockDirFail(t *testing.T) {\n\td, err := ioutil.TempDir(\"\", \"lockDir\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer func() {\n\t\terr = os.Remove(d)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}()\n\n\t_, err = LockedOpenFile(d, os.O_APPEND, 0600)\n\tif err == nil {\n\t\tt.Fatal(\"Should fail here\")\n\t}\n}", "func (lt *LockTimeout) Unlock() {\n\tatomic.StoreInt32(&lt.frontLock, 0)\n}", "func (d *dMutex) unlock(i interface{}) {\n\n\t// acquire global lock\n\td.globalMutex.Lock()\n\n\t// unlock instance mutex\n\td.mutexes[i].mutex.Unlock()\n\n\t// decrease the count, as we are no longer interested in this instance\n\t// mutex\n\td.mutexes[i].count--\n\n\t// if we are the last one interested in this instance mutex delete the\n\t// cMutex\n\tif d.mutexes[i].count == 0 {\n\t\tdelete(d.mutexes, i)\n\t}\n\n\t// release the global lock\n\td.globalMutex.Unlock()\n}", "func internalRelease(fm *filemutex.FileMutex, lfn string, log logger.Interface) error {\n\terr := fm.Close()\n\tif err != nil {\n\t\tlog.V(1).Infof(\"Error closing lock file %s: %s\", lfn, err)\n\t}\n\treturn err\n}", "func (t *Mutex) Unlock() {\n\tt.m.Lock()\n\tdefer t.m.Unlock()\n\tif !t.locked {\n\t\tpanic(\"double call to unlock\")\n\t}\n\tt.locked = false\n}", "func (s *sched) unlock(t Task) {\n\ts.cache.Del(prefixLock + t.GetID())\n}", "func (wp *WPLock) Unlock() {\n\n\twp.waitingLock.Lock()\n\tif atomic.CompareAndSwapInt32(&wp.waiting, 1, 0) {\n\t\twp.writeLock.Unlock()\n\t} else {\n\t\tatomic.AddInt32(&wp.waiting, -1)\n\t}\n\twp.waitingLock.Unlock()\n\n\twp.lock.Unlock()\n}", "func (rw *RWMutex) Unlock() {\n\trw.m.Unlock()\n\tnoteUnlock(unsafe.Pointer(rw))\n}", "func (f *File) UnlockLocal() {\n\tf.mu.Unlock()\n}", "func checkTrylockMainProcess(t *testing.T) {\n\tvar err error\n\tlockfile := lockOrFail(t)\n\tdefer removeTestLock(lockfile)\n\tlockdir := filepath.Dir(lockfile.File.Name())\n\totherAcquired, message, err := forkAndGetLock(lockdir)\n\tif err != nil {\n\t\tt.Fatalf(\"Unexpected error in subprocess trying to lock uncontested fileLock: %v. Subprocess output: %q\", err, message)\n\t}\n\tif !otherAcquired {\n\t\tt.Fatalf(\"Subprocess failed to lock uncontested fileLock. Subprocess output: %q\", message)\n\t}\n\n\terr = lockfile.tryLock()\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to lock fileLock: %v\", err)\n\t}\n\n\treacquired, message, err := forkAndGetLock(filepath.Dir(lockfile.File.Name()))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif reacquired {\n\t\tt.Fatalf(\"Permitted locking fileLock twice. Subprocess output: %q\", message)\n\t}\n\n\terr = lockfile.Unlock()\n\tif err != nil {\n\t\tt.Fatalf(\"Error unlocking fileLock: %v\", err)\n\t}\n\n\treacquired, message, err = forkAndGetLock(filepath.Dir(lockfile.File.Name()))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif !reacquired {\n\t\tt.Fatalf(\"Subprocess failed to acquire lock after it was released by the main process. Subprocess output: %q\", message)\n\t}\n}", "func (t *TrudyPipe) Unlock() {\n\tt.userMutex.Unlock()\n}", "func (vs *versionSet) logUnlock() {\n\tif !vs.writing {\n\t\tpanic(\"MANIFEST not locked for writing\")\n\t}\n\tvs.writing = false\n\tvs.writerCond.Signal()\n}", "func (r *Locking) MustUnlock() (Result, error) {\n\treturn r.delete()\n}", "func (w *Writer) lock() error {\n\tw.mutex.Lock()\n\tif w.tar == nil {\n\t\tw.mutex.Unlock()\n\t\treturn errors.New(\"Internal error: trying to use an already closed tarfile.Writer\")\n\t}\n\treturn nil\n}", "func (m *Mutex) TryRelease() bool {\n\treturn atomic.CompareAndSwapUint32(&m.l, 1, 0)\n}", "func TestUnlockUnlocked(t *testing.T) {\n\tvar mu ctxsync.Mutex\n\tassert.Panics(t, func() { mu.Unlock() })\n}", "func (m *RWMutex) NestedUnlock(i lockNameIndex) {\n\tm.mu.Unlock()\n\tlocking.DelGLock(genericMarkIndex, int(i))\n}", "func (p *pool) Unlock(user, resourceName string) error {\n\tfor k, v := range p.locks {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif k.Name != resourceName {\n\t\t\tcontinue\n\t\t}\n\n\t\tif v.User != user {\n\t\t\treturn ErrResourceLockedByDifferentUser\n\t\t}\n\n\t\tp.locks[k] = nil\n\n\t\tif err := storage.Delete(storageKey, k.Name); err != nil {\n\t\t\tlog.Error(errors.Wrap(err, \"error while storing pool lock entry\"))\n\t\t}\n\t}\n\n\treturn nil\n}", "func (c *CheckedLock) Unlock() {\n\tif !c.locked {\n\t\tBug(\"Double unlocking sync.Mutex\")\n\t}\n\tc.locked = false\n\tc.lock.Unlock()\n}", "func (f *file) Lock() error {\n\treturn nil\n}", "func (fsi *fsIOPool) Close(path string) error {\n\tfsi.Lock()\n\tdefer fsi.Unlock()\n\n\tif err := checkPathLength(path); err != nil {\n\t\treturn err\n\t}\n\n\t// Pop readers from path.\n\trlkFile, ok := fsi.readersMap[path]\n\tif !ok {\n\t\treturn nil\n\t}\n\n\t// Close the reader.\n\trlkFile.Close()\n\n\t// If the file is closed, remove it from the reader pool map.\n\tif rlkFile.IsClosed() {\n\n\t\t// Purge the cached lock path from map.\n\t\tdelete(fsi.readersMap, path)\n\t}\n\n\t// Success.\n\treturn nil\n}", "func (r *RedisLock) Unlock(ctx context.Context) error {\n\tif r.l == nil {\n\t\treturn redislock.ErrLockNotHeld\n\t}\n\n\tlockCtx, cancel := context.WithTimeout(ctx, r.ttl)\n\tdefer cancel()\n\treturn r.l.Release(lockCtx)\n}", "func (g MutexGuard[T, M]) Unlock() {\n\tg.m.Unlock()\n}", "func (kvclient *MockResKVClient) ReleaseLock(lockName string) error {\n\treturn nil\n}", "func (lr *libraryCache) Release() {\n\tlr.mtx.Lock()\n\tdefer lr.mtx.Unlock()\n\n\tif lr.refCount == 0 {\n\t\treturn\n\t}\n\n\tlr.refCount--\n\tif lr.refCount == 0 {\n\t\tos.RemoveAll(lr.path)\n\t\tlr.path = \"\"\n\t}\n}", "func (tm *TabletManager) unlock() {\n\ttm.actionSema.Release(1)\n}", "func (m *LocalDLock) Unlock(key string) error {\n\tkey = strings.ToLower(key)\n\n\tl := m.lockMeta(key)\n\tif l == nil {\n\t\treturn ErrDidNotUnlock\n\t}\n\n\tm.release(key)\n\n\treturn nil\n}", "func (l *locker) Unlock(key string) error {\n\tm, ok := l.mutexs[key]\n\tif !ok {\n\t\treturn nil\n\t}\n\tm.Unlock()\n\treturn nil\n}", "func (b *bearerTokenPolicy) unlock() {\n\tb.cond.Broadcast()\n\tb.cond.L.Unlock()\n}", "func Unlockpt(f *os.File) error {\n\tvar u int32\n\n\treturn Ioctl(f.Fd(), syscall.TIOCSPTLCK, uintptr(unsafe.Pointer(&u)))\n}", "func (v *SafeSet) Unlock() {\n\tv.mu.Unlock()\n}", "func (n *nsLockMap) unlock(volume, path, opsID string, readLock bool) {\n\tparam := nsParam{volume, path}\n\tn.lockMapMutex.RLock()\n\tnsLk, found := n.lockMap[param]\n\tn.lockMapMutex.RUnlock()\n\tif !found {\n\t\treturn\n\t}\n\tif readLock {\n\t\tnsLk.RUnlock()\n\t} else {\n\t\tnsLk.Unlock()\n\t}\n\tn.lockMapMutex.Lock()\n\tif nsLk.ref == 0 {\n\t\tlogger.LogIf(context.Background(), errors.New(\"Namespace reference count cannot be 0\"))\n\t} else {\n\t\tnsLk.ref--\n\t\tif nsLk.ref == 0 {\n\t\t\t// Remove from the map if there are no more references.\n\t\t\tdelete(n.lockMap, param)\n\t\t}\n\t}\n\tn.lockMapMutex.Unlock()\n}" ]
[ "0.7291195", "0.71327233", "0.7082573", "0.6988317", "0.6927185", "0.6922704", "0.69134337", "0.6886802", "0.6824476", "0.68202007", "0.67619586", "0.671021", "0.664967", "0.6605279", "0.6600593", "0.65595156", "0.65485597", "0.65302503", "0.65296257", "0.65162563", "0.650584", "0.6504381", "0.6480484", "0.64705074", "0.64675057", "0.6458852", "0.64481246", "0.64338285", "0.638143", "0.6354684", "0.63428164", "0.6339061", "0.631476", "0.62573177", "0.62481534", "0.6244132", "0.62358886", "0.62035346", "0.6193057", "0.6169591", "0.61688805", "0.61613", "0.61604357", "0.614922", "0.61352813", "0.6086423", "0.60356086", "0.6013359", "0.599858", "0.5996862", "0.5993351", "0.5988026", "0.5985696", "0.59848094", "0.59732866", "0.5969968", "0.59687656", "0.5961734", "0.59387684", "0.59385705", "0.5925701", "0.59152734", "0.59113944", "0.5904769", "0.5899427", "0.5891433", "0.5884989", "0.5875652", "0.5870513", "0.58533806", "0.5838645", "0.5825125", "0.5812563", "0.5799066", "0.5798249", "0.57909644", "0.57885087", "0.57752055", "0.5769993", "0.5765821", "0.5756658", "0.5753864", "0.5746041", "0.57339704", "0.5728241", "0.57267845", "0.5705784", "0.5699797", "0.56880856", "0.5686735", "0.5684433", "0.5683506", "0.5680422", "0.56758446", "0.56710863", "0.56693554", "0.56689036", "0.56662214", "0.5664744", "0.5663433" ]
0.7891906
0
NewLocalCollector returns a Collector that writes directly to a Store.
NewLocalCollector возвращает Collector, который записывает данные напрямую в Store.
func NewLocalCollector(s Store) Collector { return s }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewCollector(store *store.MemoryStore) *Collector {\n\treturn &Collector{\n\t\tstore: store,\n\t\tstopChan: make(chan struct{}),\n\t\tdoneChan: make(chan struct{}),\n\t}\n}", "func NewCollector() collector.RPCCollector {\n\treturn &storageCollector{}\n}", "func NewCollector() Collector {\n\treturn make(Collector)\n}", "func New() *Collector { return &Collector{} }", "func NewCollector(period time.Duration, collectFunc func() []Measurement) *Collector {\n\tcollector := &Collector{\n\t\tperiod: period,\n\t\tcollectFunc: collectFunc,\n\t\tlastSendingDate: -1,\n\t}\n\n\tif sources == nil {\n\t\tsources = make([]DataSource, 0)\n\t\tgo sendingLoop()\n\t}\n\n\tif UseGlobalEngine {\n\t\tcollector.Engine = Engine\n\t} else {\n\t\tcollector.Engine = &req.Engine{}\n\t}\n\n\tsources = append(sources, collector)\n\n\treturn collector\n}", "func NewLocalRouterCollector(ctx context.Context, logger *slog.Logger, errors *prometheus.CounterVec, client platform.LocalRouterClient) *LocalRouterCollector {\n\terrors.WithLabelValues(\"local_router\").Add(0)\n\n\tlocalRouterLabels := []string{\"id\", \"name\"}\n\tlocalRouterInfoLabels := append(localRouterLabels, \"tags\", \"description\")\n\tlocalRouterSwitchInfoLabels := append(localRouterLabels, \"category\", \"code\", \"zone_id\")\n\tlocalRouterServerNetworkInfoLabels := append(localRouterLabels, \"vip\", \"ipaddress1\", \"ipaddress2\", \"nw_mask_len\", \"vrid\")\n\tlocalRouterPeerLabels := append(localRouterLabels, \"peer_index\", \"peer_id\")\n\tlocalRouterPeerInfoLabels := append(localRouterPeerLabels, \"enabled\", \"description\")\n\tlocalRouterStaticRouteInfoLabels := append(localRouterLabels, \"route_index\", \"prefix\", \"next_hop\")\n\n\treturn &LocalRouterCollector{\n\t\tctx: ctx,\n\t\tlogger: logger,\n\t\terrors: errors,\n\t\tclient: client,\n\t\tUp: prometheus.NewDesc(\n\t\t\t\"sakuracloud_local_router_up\",\n\t\t\t\"If 1 the LocalRouter is available, 0 otherwise\",\n\t\t\tlocalRouterLabels, nil,\n\t\t),\n\t\tLocalRouterInfo: prometheus.NewDesc(\n\t\t\t\"sakuracloud_local_router_info\",\n\t\t\t\"A metric with a constant '1' value labeled by localRouter information\",\n\t\t\tlocalRouterInfoLabels, nil,\n\t\t),\n\t\tSwitchInfo: prometheus.NewDesc(\n\t\t\t\"sakuracloud_local_router_switch_info\",\n\t\t\t\"A metric with a constant '1' value labeled by localRouter connected switch information\",\n\t\t\tlocalRouterSwitchInfoLabels, nil,\n\t\t),\n\t\tNetworkInfo: prometheus.NewDesc(\n\t\t\t\"sakuracloud_local_router_network_info\",\n\t\t\t\"A metric with a constant '1' value labeled by network information of the localRouter\",\n\t\t\tlocalRouterServerNetworkInfoLabels, nil,\n\t\t),\n\t\tPeerInfo: prometheus.NewDesc(\n\t\t\t\"sakuracloud_local_router_peer_info\",\n\t\t\t\"A metric with a constant '1' value labeled by peer information\",\n\t\t\tlocalRouterPeerInfoLabels, nil,\n\t\t),\n\t\tPeerUp: prometheus.NewDesc(\n\t\t\t\"sakuracloud_local_router_peer_up\",\n\t\t\t\"If 1 the Peer is available, 0 otherwise\",\n\t\t\tlocalRouterPeerLabels, nil,\n\t\t),\n\t\tStaticRouteInfo: prometheus.NewDesc(\n\t\t\t\"sakuracloud_local_router_static_route_info\",\n\t\t\t\"A metric with a constant '1' value labeled by static route information\",\n\t\t\tlocalRouterStaticRouteInfoLabels, nil,\n\t\t),\n\t\tReceiveBytesPerSec: prometheus.NewDesc(\n\t\t\t\"sakuracloud_local_router_receive_per_sec\",\n\t\t\t\"Receive bytes per seconds\",\n\t\t\tlocalRouterLabels, nil,\n\t\t),\n\t\tSendBytesPerSec: prometheus.NewDesc(\n\t\t\t\"sakuracloud_local_router_send_per_sec\",\n\t\t\t\"Send bytes per seconds\",\n\t\t\tlocalRouterLabels, nil,\n\t\t),\n\t}\n}", "func New() *LocalStore {\n\treturn &LocalStore{}\n}", "func NewCollector(storageLocation v1.StorageLocation, gitter gits.Gitter, gitKind string) (Collector, error) {\n\tclassifier := storageLocation.Classifier\n\tif classifier == \"\" {\n\t\tclassifier = \"default\"\n\t}\n\tgitURL := storageLocation.GitURL\n\tif gitURL != \"\" {\n\t\treturn NewGitCollector(gitter, gitURL, storageLocation.GetGitBranch(), gitKind)\n\t}\n\tbucketProvider, err := factory.NewBucketProviderFromTeamSettingsConfigurationOrDefault(clients.NewFactory(), storageLocation)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"there was a problem obtaining the bucket provider from cluster configuratio\")\n\t}\n\treturn NewBucketCollector(storageLocation.BucketURL, classifier, bucketProvider)\n}", "func NewCollector(config *CollectorConfig) (Collector, error) {\n\tc := &standardCollector{\n\t\trunning: true,\n\t\tevents: make(chan Event, config.EventBufferSize),\n\t\tconfig: config,\n\t\tneighbors: make(map[string]neighbor),\n\t\tRWMutex: &sync.RWMutex{},\n\t}\n\n\treturn c, nil\n}", "func NewLocalStore() *LocalStore {\n\treturn &LocalStore{\n\t\tstore: make(map[string]string),\n\t\tlock: &sync.RWMutex{},\n\t}\n}", "func NewCollector(ctx context.Context, cc *collector.CollectorContext, collectDuration prometheus.Observer) prometheus.Collector {\n\treturn &StorageDomainCollector{\n\t\trootCtx: ctx,\n\t\tcc: cc,\n\t\tcollectDuration: collectDuration,\n\t}\n}", "func NewCollector() Collector {\n\treturn Collector{client: NewClient(time.Second * 5)}\n}", "func NewCollector(store *forensicstore.ForensicStore, tempDir string, definitions []goartifacts.ArtifactDefinition) (*LiveCollector, error) {\n\tprovidesMap := map[string][]goartifacts.Source{}\n\n\tdefinitions = goartifacts.FilterOS(definitions)\n\n\tfor _, definition := range definitions {\n\t\tfor _, source := range definition.Sources {\n\t\t\tfor _, provide := range source.Provides {\n\t\t\t\tkey := strings.TrimPrefix(provide.Key, \"environ_\")\n\t\t\t\tif providingSources, ok := providesMap[key]; !ok {\n\t\t\t\t\tprovidesMap[key] = []goartifacts.Source{source}\n\t\t\t\t} else {\n\t\t\t\t\tprovidesMap[key] = append(providingSources, source)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tsourceFS, err := systemfs.New()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"system fs creation failed: %w\", err)\n\t}\n\n\treturn &LiveCollector{\n\t\tSourceFS: sourceFS,\n\t\tregistryfs: registryfs.New(),\n\t\tStore: store,\n\t\tTempDir: tempDir,\n\t\tprovidesMap: providesMap,\n\t\tknowledgeBase: map[string][]string{},\n\t}, nil\n}", "func New() Collector {\n\treturn &collector{\n\t\tinner: sigar.ConcreteSigar{},\n\t}\n}", "func NewLocalAmboyStatsCollector(env cedar.Environment, id string) amboy.Job {\n\tj := makeAmboyStatsCollector()\n\tj.ExcludeRemote = true\n\tj.env = env\n\tj.SetID(fmt.Sprintf(\"%s-%s\", amboyStatsCollectorJobName, id))\n\treturn j\n}", "func NewCollector() *Collector {\n\twg := &sync.WaitGroup{}\n\tevtCh := make(chan *eventsapi.ClientEvent, collChanBufferSize)\n\n\tc := &Collector{&atomic.Value{}, wg, evtCh}\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\n\t\tvar events []*eventsapi.ClientEvent\n\t\tfor evt := range evtCh {\n\t\t\tevents = append(events, evt)\n\t\t}\n\n\t\tc.val.Store(events)\n\t}()\n\n\treturn c\n}", "func NewCollector() *Collector {\n\tcollector := &Collector{\n\t\tresults: make(chan interface{}, 100),\n\t\tdone: make(chan interface{}),\n\t}\n\tgo collector.process()\n\treturn collector\n}", "func NewLocalStore() (Store, error) {\n\t_, address := utils.StartLocalNode()\n\treturn newLocalStore(address)\n}", "func NewCollector(cl client.Client) prometheus.Collector {\n\treturn &collector{\n\t\tcl: cl,\n\t}\n}", "func NewCollector(brokerURL string, s storage.Storage) *Collector {\n\tbroker, err := NewBroker(brokerURL)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tch, err := broker.Channel()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t_, err = ch.QueueDeclare(\n\t\tspecsQueueName, // name\n\t\ttrue, // durable\n\t\tfalse, // delete when usused\n\t\tfalse, // exclusive\n\t\tfalse, // noWait\n\t\tnil, // arguments\n\t)\n\n\tdc, _ := ch.Consume(\n\t\tspecsQueueName, // queue\n\t\t\"\", // consumer\n\t\ttrue, // auto-ack\n\t\tfalse, // exclusive\n\t\tfalse, // no-local\n\t\tfalse, // no-wait\n\t\tnil, // args\n\t)\n\n\treturn &Collector{broker, ch, dc, s}\n}", "func NewCollector(api API) *Collector {\n\treturn &Collector{api: api}\n}", "func NewLocal() build_remote.ExecutionCacheServiceServer {\n\tstore, err := action.NewOnDisk()\n\tif err != nil {\n\t\tlog.Fatalf(\"could not initialise ExecutionCacheService: %v\", err)\n\t}\n\treturn &local{store}\n}", "func NewCollector() collector.RPCCollector {\n\treturn &interfaceCollector{}\n}", "func NewCollector() (prometheus.Collector, error) {\n\treturn &collector{}, nil\n}", "func NewCollector(\n\tlogger *log.Logger, server lxd.InstanceServer) prometheus.Collector {\n\treturn &collector{logger: logger, server: server}\n}", "func NewCollector() collector.RPCCollector {\n\treturn &environmentCollector{}\n}", "func NewCollector() collector.RPCCollector {\n\treturn &environmentCollector{}\n}", "func New(logger logrus.FieldLogger, conf Config) (*Collector, error) {\n\tproducer, err := sarama.NewSyncProducer(conf.Brokers, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Collector{\n\t\tProducer: producer,\n\t\tConfig: conf,\n\t\tlogger: logger,\n\t}, nil\n}", "func NewCollector(config *Config) (coll *Collector, err error) {\n\tvar gelfWriter *gelf.Writer\n\n\tif gelfWriter, err = gelf.NewWriter(config.Graylog.Address); err != nil {\n\t\treturn nil, err\n\t}\n\n\tcoll = new(Collector)\n\tcoll.writer = gelfWriter\n\tcoll.host = config.Collector.Hostname\n\n\treturn coll, nil\n}", "func NewUseCollector() *Use {\n\treturn &Use{}\n}", "func NewCollector(cfg *config.AgentConfig) TelemetryCollector {\n\tif !cfg.TelemetryConfig.Enabled {\n\t\treturn &noopTelemetryCollector{}\n\t}\n\n\tvar endpoints []config.Endpoint\n\tfor _, endpoint := range cfg.TelemetryConfig.Endpoints {\n\t\tu, err := url.Parse(endpoint.Host)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tu.Path = \"/api/v2/apmtelemetry\"\n\t\tendpointWithPath := *endpoint\n\t\tendpointWithPath.Host = u.String()\n\n\t\tendpoints = append(endpoints, endpointWithPath)\n\t}\n\n\treturn &telemetryCollector{\n\t\tclient: cfg.NewHTTPClient(),\n\t\tendpoints: endpoints,\n\t\tuserAgent: fmt.Sprintf(\"Datadog Trace Agent/%s/%s\", cfg.AgentVersion, cfg.GitCommit),\n\n\t\tcfg: cfg,\n\t\tcollectedStartupError: &atomic.Bool{},\n\t}\n}", "func NewCollector(client *api.Client, collectSnaphots, collectNetwork bool) prometheus.Collector {\n\treturn &VMCollector{client: client, collectSnapshots: collectSnaphots, collectNetwork: collectNetwork}\n}", "func NewCollector(cfg *config.AgentConfig, ctx context.Context) (Collector, error) {\n\tsysInfo, err := checks.CollectSystemInfo(cfg)\n\tif err != nil {\n\t\treturn Collector{}, err\n\t}\n\n\tenabledChecks := make([]checks.Check, 0)\n\tfor _, c := range checks.All {\n\t\tif cfg.CheckIsEnabled(c.Name()) {\n\t\t\tc.Init(cfg, sysInfo)\n\t\t\tenabledChecks = append(enabledChecks, c)\n\t\t}\n\t}\n\n\treturn NewCollectorWithChecks(cfg, enabledChecks, ctx), nil\n}", "func NewCollector(username string, token string, source string, timeout time.Duration, waitGroup *sync.WaitGroup) Collector {\n\treturn &collector{\n\t\turl: metricsEndpont,\n\t\tusername: username,\n\t\ttoken: token,\n\t\tsource: source,\n\t\ttimeout: timeout,\n\n\t\thttpClient: &http.Client{\n\t\t\tTimeout: time.Second * 30,\n\t\t},\n\t\twaitGroup: waitGroup,\n\t\tstop: make(chan bool),\n\t\tbuffer: make(chan gauge, 10000),\n\t}\n}", "func newLocalStore(address net.Address) (Store, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\tsession, err := primitive.NewSession(ctx, primitive.Partition{ID: 1, Address: address})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tupdatesName := primitive.Name{\n\t\tNamespace: \"local\",\n\t\tName: primitiveName,\n\t}\n\tupdates, err := _map.New(context.Background(), updatesName, []*primitive.Session{session})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &atomixStore{\n\t\tupdates: updates,\n\t}, nil\n}", "func New(ctx context.Context, local bool) (*store, error) {\n\tts, err := google.DefaultTokenSource(ctx, auth.ScopeFullControl)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Problem setting up client OAuth: %s\", err)\n\t}\n\tclient := httputils.DefaultClientConfig().WithTokenSource(ts).With2xxOnly().Client()\n\tstorageClient, err := storage.NewClient(context.Background(), option.WithHTTPClient(client))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Problem creating storage client: %s\", err)\n\t}\n\tcache, err := lru.New(LRU_CACHE_SIZE)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed creating cache: %s\", err)\n\t}\n\treturn &store{\n\t\tbucket: storageClient.Bucket(FIDDLE_STORAGE_BUCKET),\n\t\tcache: cache,\n\t}, nil\n}", "func NewRemoteCollector(addr string) *RemoteCollector {\n\treturn &RemoteCollector{\n\t\taddr: addr,\n\t\tdial: func() (net.Conn, error) {\n\t\t\treturn net.Dial(\"tcp\", addr)\n\t\t},\n\t}\n}", "func NewLocal(label string) *Local {\n\treturn &Local{Root: configdir.LocalCache(label)}\n}", "func New(client *statsd.Client, interval time.Duration) *Collector {\n\treturn &Collector{\n\t\tinterval: interval,\n\t\tclient: client,\n\t\tdone: make(chan struct{}),\n\t}\n}", "func NewSystemCollector() Collector {\n\treturn &SystemCollector{}\n}", "func NewCollector() collector.RPCCollector {\n\treturn &vpwsCollector{}\n}", "func New(computeAPI ComputeAPI, dnsAPI DNSAPI, removalPredicate IPAddressRemovalPredicate) *Collector {\n\treturn &Collector{computeAPI, dnsAPI, removalPredicate}\n}", "func NewCollector(rcClientId string, kubernetesClusterId string) TelemetryCollector {\n\treturn &telemetryCollector{\n\t\tclient: httputils.NewResetClient(httpClientResetInterval, httpClientFactory(httpClientTimeout)),\n\t\thost: utils.GetMainEndpoint(config.Datadog, mainEndpointPrefix, mainEndpointUrlKey),\n\t\tuserAgent: \"Datadog Cluster Agent\",\n\t\trcClientId: rcClientId,\n\t\tkubernetesClusterId: kubernetesClusterId,\n\t}\n}", "func NewCollector(l *logrus.Entry, updateInterval time.Duration) *Collector {\n\tcol := &Collector{\n\t\tMsgEvtChan: make(chan *discordgo.Message, 1000),\n\t\tinterval: updateInterval,\n\t\tl: l,\n\t\tchannels: make(map[int64]*entry),\n\t}\n\n\tgo col.run()\n\n\treturn col\n}", "func NewCollector() collector.RPCCollector {\n\treturn &accountingCollector{}\n}", "func NewCollector(logicalSystem string) collector.RPCCollector {\n\treturn &bgpCollector{LogicalSystem: logicalSystem}\n}", "func New(capacity int64) chainstore.Store {\n\tmemStore := &memStore{\n\t\tdata: make(map[string][]byte, 1000),\n\t}\n\tstore := lrumgr.New(capacity, memStore)\n\treturn store\n}", "func Local() Storage {\n\treturn local.New()\n}", "func NewLocal() Local {\n\treturn Local{}\n}", "func NewLocalCollection(path string, pattern string) Collection {\n\tr, _ := regexp.Compile(pattern)\n\treturn LocalCollection{\n\t\tPath: path,\n\t\tFilterable: Filterable{r}}\n}", "func NewCollector(cm *clientmanager.ClientManager) prometheus.Collector {\n\treturn &grpcClientManagerCollector{\n\t\tcm: cm,\n\t}\n}", "func NewCollector(defaultGroup string) *MemoryMetricsCollector {\n\treturn &MemoryMetricsCollector{defaultGroup: defaultGroup, metrics: make([]operation.MetricOperation, 0)}\n}", "func NewStatsCollector(cliContext *cli.Context) (*StatsCollector, error) {\n\n\t// fill the Collector struct\n\tcollector := &StatsCollector{\n\t\tcliContext: cliContext,\n\t\tsocketPath: cliContext.String(\"socketPath\"),\n\t\tkamailioHost: cliContext.String(\"host\"),\n\t\tkamailioPort: cliContext.Int(\"port\"),\n\t}\n\n\t// fine, return the created object struct\n\treturn collector, nil\n}", "func NewStringCollector(name, help string) *StringCollector {\n\treturn &StringCollector{\n\t\tname: name,\n\t\thelp: help,\n\t\tvalue: \"\",\n\t}\n}", "func NewVMwareCollector(ctx *pulumi.Context,\n\tname string, args *VMwareCollectorArgs, opts ...pulumi.ResourceOption) (*VMwareCollector, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.ProjectName == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'ProjectName'\")\n\t}\n\tif args.ResourceGroupName == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'ResourceGroupName'\")\n\t}\n\taliases := pulumi.Aliases([]pulumi.Alias{\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:migrate:VMwareCollector\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-native:migrate/v20191001:VMwareCollector\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:migrate/v20191001:VMwareCollector\"),\n\t\t},\n\t})\n\topts = append(opts, aliases)\n\tvar resource VMwareCollector\n\terr := ctx.RegisterResource(\"azure-native:migrate:VMwareCollector\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (s StructuredSyslog) New() cue.Collector {\n\tif s.App == \"\" {\n\t\tlog.Warn(\"StructuredSyslog.New called to created a collector, but App param is empty. Returning nil collector.\")\n\t\treturn nil\n\t}\n\n\tvar err error\n\tif s.Network == \"\" || s.Address == \"\" {\n\t\ts.Network, s.Address, err = localSyslog()\n\t}\n\tif err != nil {\n\t\tlog.Warn(\"StructuredSyslog.New called to created a collector, but Network or Address param is empty. Couldn't find a local syslog socket either. Returning nil collector.\")\n\t\treturn nil\n\t}\n\n\treturn &structuredCollector{\n\t\tStructuredSyslog: s,\n\t\tsocket: Socket{\n\t\t\tFormatter: structuredFormatter(s.Facility, s.App, s.MessageFormatter, s.StructuredFormatter, s.ID, s.WriteBOM),\n\t\t\tNetwork: s.Network,\n\t\t\tAddress: s.Address,\n\t\t\tTLS: s.TLS,\n\t\t}.New(),\n\t}\n}", "func NewLocalStore(meta Container, storage LocalStorage, pd Prophet) LocalStore {\n\treturn &defaultLocalStore{\n\t\tmeta: meta,\n\t\tdb: &defaultLocalDB{storage: storage},\n\t\tpd: pd,\n\t}\n}", "func NewDirCollector() DirCollector {\n\treturn make(DirCollector)\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 New(log log.Logger, c *Config) (integrations.Integration, error) {\n\tconfigMap := exporter.GenerateConfigs()\n\tc.applyConfig(configMap)\n\twc, err := exporter.NewWindowsCollector(c.Name(), c.EnabledCollectors, configMap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_ = level.Info(log).Log(\"msg\", \"Enabled windows_exporter collectors\")\n\treturn integrations.NewCollectorIntegration(c.Name(), integrations.WithCollectors(wc)), nil\n}", "func NewSynchronizedCollector(coll Collector) Collector {\n\treturn &synchronizedCollector{\n\t\tCollector: coll,\n\t}\n}", "func New(options ...LocalCacheOption) *LocalCache {\n\tc := LocalCache{\n\t\tData: make(map[interface{}]*Value),\n\t\tLRU: NewLRUQueue(),\n\t}\n\tc.Sweeper = async.NewInterval(c.Sweep, 500*time.Millisecond)\n\tfor _, opt := range options {\n\t\topt(&c)\n\t}\n\treturn &c\n}", "func NewLocalProvider(t []string) Provider {\n\treturn newLocalProviderWithClock(t, clock.New())\n}", "func NewMetricCollector(logger *zap.SugaredLogger) *MetricCollector {\n\tcollector := &MetricCollector{\n\t\tlogger: logger,\n\t\tcollections: make(map[string]*collection),\n\t}\n\n\treturn collector\n}", "func New() *CPUCollector {\n\tcpuMetrics := newCPUMetrics()\n\tcpuStats := cpuclient.New()\n\n\treturn &CPUCollector{\n\t\tcpuMetrics: cpuMetrics,\n\t\tcpuStats: cpuStats,\n\t}\n}", "func NewSyncCollector() *SyncCollector {\n\tso := SyncCollector{c: make(Collector)}\n\treturn &so\n}", "func NewCollector() collector.RPCCollector {\n\treturn &isisCollector{}\n}", "func NewServer(l net.Listener, c Collector) *CollectorServer {\n\tcs := &CollectorServer{c: c, l: l}\n\treturn cs\n}", "func GetCollector() *Collector {\n\tif collector == nil {\n\t\tlogger.Errorf(\"Collector need to be init correctly\")\n\t\treturn collector\n\t}\n\n\treturn collector\n}", "func (c *ClusterScalingScheduleCollectorPlugin) NewCollector(hpa *autoscalingv2.HorizontalPodAutoscaler, config *MetricConfig, interval time.Duration) (Collector, error) {\n\treturn NewClusterScalingScheduleCollector(c.store, c.defaultScalingWindow, c.defaultTimeZone, c.rampSteps, c.now, hpa, config, interval)\n}", "func NewStorageCollector(config []byte) (Collector, error) {\n\tslaunch.Debug(\"New Storage Collector initialized\\n\")\n\tsc := new(StorageCollector)\n\terr := json.Unmarshal(config, &sc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn sc, nil\n}", "func MakeContextCollector(shipper ContextShipper, defaultTTL time.Duration) *ContextCollector {\n\tc := &ContextCollector{\n\t\tLogger: log.WithFields(log.Fields{\n\t\t\t\"domain\": \"context\",\n\t\t}),\n\t\tCache: cache.New(defaultTTL, defaultTTL),\n\t\tMarked: make(map[string]struct{}),\n\t\ti: 0,\n\t\tShip: shipper,\n\t\tFlowListeners: make([]chan types.Entry, 0),\n\t}\n\tc.Logger.Debugf(\"created cache with default TTL %v\", defaultTTL)\n\treturn c\n}", "func NewLocalFetcher() *LocalFetcher {\n\treturn &LocalFetcher{\n\t\tdata: make(map[string]*asset.Asset),\n\t}\n}", "func NewFileLocalStore(dir string) FileStore {\n\treturn &fileLocalStore{\n\t\tdir: dir,\n\t\tname: make(map[string]string),\n\t}\n}", "func New(domains []string, outputLocation string, prefix string) *provider.Provider {\n\tloc := &Local{\n\t\tdomains: domains,\n\t\tprefix: prefix,\n\t\toutputLocation: outputLocation,\n\t}\n\tprov := provider.Provider(loc)\n\treturn &prov\n}", "func NewFileCollector() FileCollector {\n\treturn make(FileCollector)\n}", "func (m *LocalManager) New(ctx context.Context, id string) (linker.Storage, error) {\n\tdb, err := NewLocalStorage(ctx, fmt.Sprintf(\"%s/db-%s\", m.path, id))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn db, nil\n}", "func NewLibvirtCollector() *Libvirt {\n\treturn &Libvirt{}\n\n}", "func NewNFSCollector(g getNFSStats) *nfsCollector {\n\treturn &nfsCollector{\n\t\tg,\n\t}\n}", "func NewCollector(config CollectorConfig, rawConfig *common.Config) (*Collector, error) {\n\n\t// Compile the configured pattern\n\tpattern, err := regexp.Compile(config.Pattern)\n\tif err != nil {\n\t\tlogp.Warn(\"Unable to parse regular expression: %s\", err)\n\t\treturn nil, err\n\t}\n\n\t// Create our Collector with its channel signals\n\tcollector := Collector{\n\t\tPattern: pattern,\n\t\tconfig: config,\n\n\t\tprospectorDone: make(chan struct{}),\n\t\tlines: make(chan string),\n\t\tDone: make(chan struct{}),\n\t\tStopped: make(chan struct{}),\n\t}\n\n\t// Initialize our ticker for handling timeouts\n\tif config.Timeout.Interval > 0 {\n\t\t// If a timeout is set then create a new ticker and save wrap its channel with a variable\n\t\tcollector.ticker = time.NewTicker(config.Timeout.Interval)\n\t\tcollector.timeoutChannel = collector.ticker.C\n\t} else {\n\t\t// If a timeout is not set then create just a generic channel that will never return.\n\t\t// It just makes generalizing the code easier.\n\t\tcollector.timeoutChannel = make(chan time.Time)\n\t}\n\n\t// Configure a new FileBeat Prospector with our rawConfig that will send it's data to a\n\t// CollectorOutleter\n\tp, err := prospector.NewProspector(\n\t\trawConfig,\n\t\tcollector.collectorOutleterFactory,\n\t\tcollector.prospectorDone,\n\t\t[]file.State{},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcollector.prospector = p\n\treturn &collector, nil\n}", "func NewLocalDelivery(st mailstore.Store, fpath string) DeliverJob {\n\treturn &LocalDeliverJob{\n\t\tst: st,\n\t\tresult: make(chan bool),\n\t\tfpath: fpath,\n\t}\n}", "func NewLocalSnapStore(prefix string) (*LocalSnapStore, error) {\n\tif len(prefix) != 0 {\n\t\terr := os.MkdirAll(prefix, 0700)\n\t\tif err != nil && !os.IsExist(err) {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn &LocalSnapStore{\n\t\tprefix: prefix,\n\t}, nil\n}", "func NewCollector(bindIP, port string) (*SyslogCollector, error) {\n\tdefer TRA(CE())\n\tchannel := make(syslog.LogPartsChannel)\n\tsysServ := syslog.NewServer()\n\tsysServ.SetHandler(syslog.NewChannelHandler(channel))\n\t// uses RFC3164 because it is default for rsyslog\n\tsysServ.SetFormat(syslog.RFC3164)\n\terr := sysServ.ListenUDP(fmt.Sprintf(\"%s:%s\", bindIP, port))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgo func(channel syslog.LogPartsChannel) {\n\t\tfor logEntry := range channel {\n\t\t\tinfo, err := ctl.NewHostInfo()\n\t\t\tif err != nil {\n\t\t\t\tinfo = &ctl.HostInfo{}\n\t\t\t}\n\t\t\tevent, err := ctl.NewEvent(logEntry, *info)\n\t\t\tif err != nil {\n\t\t\t\tErrorLogger.Printf(\"cannot format syslog entry: %s\\n\", err)\n\t\t\t}\n\t\t\terr = event.Save(SubmitPath())\n\t\t\tif err != nil {\n\t\t\t\tErrorLogger.Printf(\"cannot save syslog entry to file: %s\\n\", err)\n\t\t\t}\n\t\t}\n\t}(channel)\n\treturn &SyslogCollector{\n\t\tserver: sysServ,\n\t\tport: port,\n\t}, nil\n}", "func New(cf Config) cache.Cache {\n\treturn &localCache{\n\t\tcacheEngine: freecache.NewCache(cf.Size),\n\t\tcf: cf,\n\t}\n}", "func NewCollector(url, token, xSecret string) (*Collector, error) {\n\tc := Collector{}\n\n\tif url == \"\" {\n\t\treturn nil, fmt.Errorf(\"URL should not be empty\")\n\t}\n\tc.dadataAPIURL = url\n\tif token == \"\" {\n\t\treturn nil, fmt.Errorf(\"Token should not be empty. Please specify it via DADATA_TOKEN env var\")\n\t}\n\tc.dadataToken = token\n\tif xSecret == \"\" {\n\t\treturn nil, fmt.Errorf(\"X-Secret should not be empty. Please specify it via DADATA_X_SECRET env var\")\n\t}\n\tc.dadataXSecret = xSecret\n\n\terr := c.dadataCheck()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc.totalScrapes = prometheus.NewCounter(prometheus.CounterOpts{\n\t\tNamespace: namespace,\n\t\tName: \"exporter_scrapes_total\",\n\t\tHelp: \"Count of total scrapes\",\n\t})\n\n\tc.failedBalanceScrapes = prometheus.NewCounter(prometheus.CounterOpts{\n\t\tNamespace: namespace,\n\t\tName: \"exporter_failed_balance_scrapes_total\",\n\t\tHelp: \"Count of failed balance scrapes\",\n\t})\n\n\tc.failedStatsScrapes = prometheus.NewCounter(prometheus.CounterOpts{\n\t\tNamespace: namespace,\n\t\tName: \"exporter_failed_stats_scrapes_total\",\n\t\tHelp: \"Count of failed stats scrapes\",\n\t})\n\n\tc.CurrentBalance = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace: namespace,\n\t\tName: \"current_balance\",\n\t\tHelp: \"Current balance on Dadata\",\n\t})\n\n\tc.ServicesMerging = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: \"services\",\n\t\tName: \"merging_total\",\n\t\tHelp: \"Merging count for today\",\n\t})\n\n\tc.ServicesSuggestions = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: \"services\",\n\t\tName: \"suggestions_total\",\n\t\tHelp: \"Suggestions count for today\",\n\t})\n\n\tc.ServicesClean = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: \"services\",\n\t\tName: \"clean_total\",\n\t\tHelp: \"Clean count for today\",\n\t})\n\n\treturn &c, nil\n}", "func New(cfg Collector, nodeInfo collectors.NodeInfo, rels *ContainerTaskRels) (Collector, chan producers.MetricsMessage) {\n\tc := cfg\n\tc.log = logrus.WithFields(logrus.Fields{\"collector\": \"mesos-agent\"})\n\tc.nodeInfo = nodeInfo\n\tc.metricsChan = make(chan producers.MetricsMessage)\n\tc.ContainerTaskRels = rels\n\treturn c, c.metricsChan\n}", "func newPoolCollector(config monitoring.MetricsConfig, logger *zap.Logger,\n\tspectrumClient spectrumservice.Client) (Collector, error) {\n\n\tlabelPool := []string{\"pool_name\", \"storage_system\"}\n\n\tproperties := make(map[string]*prometheus.Desc)\n\n\tfor _, p := range config.Metrics.Pools.Properties {\n\t\tproperties[p.PropertyName] = prometheus.NewDesc(p.PrometheusName, p.PrometheusHelp, labelPool, nil)\n\t}\n\n\treturn &poolCollector{\n\t\tibmSpectrumClient: spectrumClient,\n\t\tlogger: logger.Sugar(),\n\t\tproperties: properties,\n\t}, nil\n}", "func NewLocal() ILocal {\n\treturn &Local{}\n}", "func NewCollector(dyno *Dynomite) *Collector {\n\treturn &Collector{\n\t\tdyno: dyno,\n\t\tstate: typedDesc{\n\t\t\tdesc: prometheus.NewDesc(\n\t\t\t\t\"dynomite_state\",\n\t\t\t\t\"State as reported by Dynomite.\",\n\t\t\t\t[]string{\"state\", \"rack\", \"dc\", \"token\", \"ip_address\"}, nil),\n\t\t\tvalueType: prometheus.GaugeValue,\n\t\t},\n\t\tdbSize: typedDesc{\n\t\t\tdesc: prometheus.NewDesc(\n\t\t\t\t\"dynomite_db_size\",\n\t\t\t\t\"Key database size as reported by the Redis backend.\",\n\t\t\t\t[]string{\"rack\", \"dc\", \"token\", \"ip_address\"}, nil),\n\t\t\tvalueType: prometheus.GaugeValue,\n\t\t},\n\t\tuptime: typedDesc{\n\t\t\tdesc: prometheus.NewDesc(\n\t\t\t\t\"dynomite_uptime\",\n\t\t\t\t\"Uptime as reported by Dynomite info.\",\n\t\t\t\t[]string{\"rack\", \"dc\", \"token\", \"ip_address\"}, nil),\n\t\t\tvalueType: prometheus.GaugeValue,\n\t\t},\n\t\tclientConnections: typedDesc{\n\t\t\tdesc: prometheus.NewDesc(\n\t\t\t\t\"dynomite_client_connections\",\n\t\t\t\t\"Client connections as reported by Dynomite info.\",\n\t\t\t\t[]string{\"rack\", \"dc\", \"token\", \"ip_address\"}, nil),\n\t\t\tvalueType: prometheus.GaugeValue,\n\t\t},\n\t\tclientReadRequests: typedDesc{\n\t\t\tdesc: prometheus.NewDesc(\n\t\t\t\t\"dynomite_client_read_requests\",\n\t\t\t\t\"Client read requests as reported by Dynomite info.\",\n\t\t\t\t[]string{\"rack\", \"dc\", \"token\", \"ip_address\"}, nil),\n\t\t\tvalueType: prometheus.GaugeValue,\n\t\t},\n\t\tclientWriteRequests: typedDesc{\n\t\t\tdesc: prometheus.NewDesc(\n\t\t\t\t\"dynomite_client_write_requests\",\n\t\t\t\t\"Client write requests as reported by Dynomite info.\",\n\t\t\t\t[]string{\"rack\", \"dc\", \"token\", \"ip_address\"}, nil),\n\t\t\tvalueType: prometheus.GaugeValue,\n\t\t},\n\t\tclientDroppedRequests: typedDesc{\n\t\t\tdesc: prometheus.NewDesc(\n\t\t\t\t\"dynomite_client_dropped_requests\",\n\t\t\t\t\"Client dropped requests as reported by Dynomite info.\",\n\t\t\t\t[]string{\"rack\", \"dc\", \"token\", \"ip_address\"}, nil),\n\t\t\tvalueType: prometheus.GaugeValue,\n\t\t},\n\t}\n}", "func NewCollector(m Metric) (prometheus.Collector, error) {\n\tif len(m.Name) == 0 {\n\t\treturn nil, errors.New(\"A name is required for a metric\")\n\t}\n\n\tvar (\n\t\tnamespace = m.Namespace\n\t\tsubsystem = m.Subsystem\n\t\thelp = m.Help\n\t)\n\n\tif len(namespace) == 0 {\n\t\tnamespace = DefaultNamespace\n\t}\n\n\tif len(subsystem) == 0 {\n\t\tsubsystem = DefaultSubsystem\n\t}\n\n\tif len(help) == 0 {\n\t\thelp = m.Name\n\t}\n\n\tswitch m.Type {\n\tcase CounterType:\n\t\treturn prometheus.NewCounterVec(prometheus.CounterOpts{\n\t\t\tNamespace: namespace,\n\t\t\tSubsystem: subsystem,\n\t\t\tName: m.Name,\n\t\t\tHelp: help,\n\t\t\tConstLabels: prometheus.Labels(m.ConstLabels),\n\t\t}, m.LabelNames), nil\n\n\tcase GaugeType:\n\t\treturn prometheus.NewGaugeVec(prometheus.GaugeOpts{\n\t\t\tNamespace: namespace,\n\t\t\tSubsystem: subsystem,\n\t\t\tName: m.Name,\n\t\t\tHelp: help,\n\t\t\tConstLabels: prometheus.Labels(m.ConstLabels),\n\t\t}, m.LabelNames), nil\n\n\tcase HistogramType:\n\t\treturn prometheus.NewHistogramVec(prometheus.HistogramOpts{\n\t\t\tNamespace: namespace,\n\t\t\tSubsystem: subsystem,\n\t\t\tName: m.Name,\n\t\t\tHelp: help,\n\t\t\tBuckets: m.Buckets,\n\t\t\tConstLabels: prometheus.Labels(m.ConstLabels),\n\t\t}, m.LabelNames), nil\n\n\tcase SummaryType:\n\t\treturn prometheus.NewSummaryVec(prometheus.SummaryOpts{\n\t\t\tNamespace: namespace,\n\t\t\tSubsystem: subsystem,\n\t\t\tName: m.Name,\n\t\t\tHelp: help,\n\t\t\tObjectives: m.Objectives,\n\t\t\tMaxAge: m.MaxAge,\n\t\t\tAgeBuckets: m.AgeBuckets,\n\t\t\tBufCap: m.BufCap,\n\t\t\tConstLabels: prometheus.Labels(m.ConstLabels),\n\t\t}, m.LabelNames), nil\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unsupported metric type: %s\", m.Type)\n\t}\n}", "func NewLocalUploader(\n\tbackupStoreDAL *dal.IntelligentStoreDAL,\n\tbackupBucketName,\n\tbackupFromLocation string,\n\tincludeMatcher,\n\texcludeMatcher patternmatcher.Matcher,\n\tbackupDryRun bool,\n) *LocalUploader {\n\n\treturn &LocalUploader{\n\t\tbackupStoreDAL,\n\t\tbackupBucketName,\n\t\tbackupFromLocation,\n\t\tincludeMatcher,\n\t\texcludeMatcher,\n\t\tgofs.NewOsFs(),\n\t\tbackupDryRun,\n\t}\n}", "func NewDfCollector() *DfCollector {\n\treturn &DfCollector{}\n}", "func NewTLSRemoteCollector(addr string, tlsConfig *tls.Config) *RemoteCollector {\n\treturn &RemoteCollector{\n\t\taddr: addr,\n\t\tdial: func() (net.Conn, error) {\n\t\t\treturn tls.Dial(\"tcp\", addr, tlsConfig)\n\t\t},\n\t}\n}", "func NewLocalFileStore(baseDir OsPath) (FileStore, error) {\n\tbase, err := checkIsDir(string(baseDir))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &fileStore{base}, nil\n}", "func (c *ScalingScheduleCollectorPlugin) NewCollector(hpa *autoscalingv2.HorizontalPodAutoscaler, config *MetricConfig, interval time.Duration) (Collector, error) {\n\treturn NewScalingScheduleCollector(c.store, c.defaultScalingWindow, c.defaultTimeZone, c.rampSteps, c.now, hpa, config, interval)\n}", "func New(chromePerf anomalies.Store) (*store, error) {\n\tcache, err := lru.New(cacheSize)\n\tif err != nil {\n\t\treturn nil, skerr.Wrapf(err, \"Failed to create anomaly store cache.\")\n\t}\n\n\t// cleanup the lru cache periodically.\n\tgo func() {\n\t\tfor range time.Tick(cacheCleanupPeriod) {\n\t\t\tcleanupCache(cache)\n\t\t}\n\t}()\n\n\tret := &store{\n\t\tcache: cache,\n\t\tnumEntriesInCache: metrics2.GetInt64Metric(\"anomaly_store_num_entries_in_cache\"),\n\t\tChromePerf: chromePerf,\n\t}\n\treturn ret, nil\n}", "func registerCollector(name string, factory func() (Collector, error)) {\n\tcollectorFactories[name] = factory\n}", "func NewStaticCollector(m map[string]string) func() sstable.TablePropertyCollector {\n\treturn func() sstable.TablePropertyCollector { return &staticCollector{m} }\n}", "func NewCollectorCache(collector Collector) Collector {\n\treturn &collectorCache{\n\t\tcollector: collector,\n\t\tcache: NewCache(cacheGCInterval),\n\t}\n}", "func NewFileCollector(name string, limit Size, pipe bool) File {\n\treturn &FileCollector{Name: name, Limit: limit, Pipe: pipe}\n}" ]
[ "0.7043134", "0.6845503", "0.6701996", "0.6606692", "0.6517277", "0.6481328", "0.63933116", "0.6308921", "0.62407637", "0.62237227", "0.6169103", "0.6142803", "0.6077568", "0.60701793", "0.60639817", "0.6062933", "0.60500205", "0.6038892", "0.5981425", "0.59649676", "0.5927517", "0.5884676", "0.5883424", "0.5869342", "0.58594537", "0.5856504", "0.5856504", "0.5850362", "0.58215505", "0.5789103", "0.57841337", "0.5781289", "0.5766688", "0.5732893", "0.57091516", "0.5677057", "0.5668884", "0.56606346", "0.5658218", "0.56494427", "0.5642903", "0.5592421", "0.5578773", "0.5561492", "0.5549838", "0.5547447", "0.55441517", "0.5532109", "0.5489043", "0.546016", "0.54344803", "0.5426006", "0.54166794", "0.5413834", "0.54102", "0.5406808", "0.5404807", "0.5383488", "0.53774095", "0.53678614", "0.5365773", "0.5359167", "0.53506106", "0.533421", "0.5324231", "0.5292647", "0.5270657", "0.52583665", "0.5254834", "0.5248841", "0.52475256", "0.5244337", "0.52362895", "0.5209069", "0.5207019", "0.5206861", "0.52012616", "0.5190359", "0.5186415", "0.51676637", "0.5162739", "0.5158268", "0.51528925", "0.5136553", "0.5135053", "0.513181", "0.5122861", "0.509565", "0.5092019", "0.5090524", "0.50827634", "0.5078538", "0.5059154", "0.50563496", "0.5052611", "0.50418246", "0.49995375", "0.4985796", "0.49830183", "0.497285" ]
0.8576599
0
newCollectPacket returns an initialized wire.CollectPacket given a span and set of annotations.
newCollectPacket возвращает инициализированный wire.CollectPacket, заданный спаном и набором аннотаций.
func newCollectPacket(s SpanID, as Annotations) *wire.CollectPacket { return &wire.CollectPacket{ Spanid: s.wire(), Annotation: as.wire(), } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (cc *ChunkedCollector) Collect(span SpanID, anns ...Annotation) error {\n\tcc.mu.Lock()\n\tdefer cc.mu.Unlock()\n\n\tif cc.stopped {\n\t\treturn errors.New(\"ChunkedCollector is stopped\")\n\t}\n\tif !cc.started {\n\t\tcc.start()\n\t}\n\n\tif cc.pendingBySpanID == nil {\n\t\tcc.pendingBySpanID = map[SpanID]*wire.CollectPacket{}\n\t}\n\n\tif p, present := cc.pendingBySpanID[span]; present {\n\t\tif len(anns) > 0 {\n\t\t\tp.Annotation = append(p.Annotation, Annotations(anns).wire()...)\n\t\t}\n\t} else {\n\t\tcc.pendingBySpanID[span] = newCollectPacket(span, anns)\n\t\tcc.pending = append(cc.pending, span)\n\t}\n\n\tif err := cc.lastErr; err != nil {\n\t\tcc.lastErr = nil\n\t\treturn err\n\t}\n\treturn nil\n}", "func (rc *RemoteCollector) Collect(span SpanID, anns ...Annotation) error {\n\treturn rc.collectAndRetry(newCollectPacket(span, anns))\n}", "func New() *Collector { return &Collector{} }", "func New(computeAPI ComputeAPI, dnsAPI DNSAPI, removalPredicate IPAddressRemovalPredicate) *Collector {\n\treturn &Collector{computeAPI, dnsAPI, removalPredicate}\n}", "func NewCollect() *cobra.Command {\n\tcollectOptions := newCollectOptions()\n\n\tcmd := &cobra.Command{\n\t\tUse: \"collect\",\n\t\tShort: \"Obtain all the data of the current node\",\n\t\tLong: edgecollectLongDescription,\n\t\tExample: edgecollectExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\terr := ExecuteCollect(collectOptions)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t}\n\t\t},\n\t}\n\tcmd.AddCommand()\n\taddCollectOtherFlags(cmd, collectOptions)\n\treturn cmd\n}", "func NewCreateCollectInfoRequestWithoutParam() *CreateCollectInfoRequest {\n\n return &CreateCollectInfoRequest{\n JDCloudRequest: core.JDCloudRequest{\n URL: \"/regions/{regionId}/logtopics/{logtopicUID}/collectinfos\",\n Method: \"POST\",\n Header: nil,\n Version: \"v1\",\n },\n }\n}", "func New(token string, collectionID string) *SpanListener {\n\treturn &SpanListener{\n\t\tToken: token,\n\t\tCollectionID: collectionID,\n\t\tmeasurementCh: make(chan *apipb.CarrierModuleMeasurements),\n\t}\n}", "func New() Collector {\n\treturn &collector{\n\t\tinner: sigar.ConcreteSigar{},\n\t}\n}", "func NewUnReportStatsCollect(storeID uint64, regionIDs map[uint64]struct{}, interval uint64) *FlowItem {\n\treturn &FlowItem{\n\t\tpeerInfo: nil,\n\t\tregionInfo: nil,\n\t\texpiredStat: nil,\n\t\tunReportStatsCollect: &unReportStatsCollect{\n\t\t\tstoreID: storeID,\n\t\t\tregionIDs: regionIDs,\n\t\t\tinterval: interval,\n\t\t},\n\t}\n}", "func NewPacket(data []byte, len uint32) *Packet {\n\treturn &Packet{\n\t\tTime: time.Now(),\n\t\tCaplen: len,\n\t\tLen: len,\n\t\tData: data,\n\t}\n}", "func NewSpan(name errors.Op) (*Metric, *Span) {\n\tm := New(name)\n\treturn m, m.StartSpan(name)\n}", "func NewCollector(period time.Duration, collectFunc func() []Measurement) *Collector {\n\tcollector := &Collector{\n\t\tperiod: period,\n\t\tcollectFunc: collectFunc,\n\t\tlastSendingDate: -1,\n\t}\n\n\tif sources == nil {\n\t\tsources = make([]DataSource, 0)\n\t\tgo sendingLoop()\n\t}\n\n\tif UseGlobalEngine {\n\t\tcollector.Engine = Engine\n\t} else {\n\t\tcollector.Engine = &req.Engine{}\n\t}\n\n\tsources = append(sources, collector)\n\n\treturn collector\n}", "func newCollectionStatsCollector(ctx context.Context, client *mongo.Client, logger *logrus.Logger, compatible, discovery bool, topology labelsGetter, collections []string) *collstatsCollector {\n\treturn &collstatsCollector{\n\t\tctx: ctx,\n\t\tbase: newBaseCollector(client, logger),\n\n\t\tcompatibleMode: compatible,\n\t\tdiscoveringMode: discovery,\n\t\ttopologyInfo: topology,\n\n\t\tcollections: collections,\n\t}\n}", "func Collect(collectionLimit int) *sif.DataFrameOperation {\n\treturn &sif.DataFrameOperation{\n\t\tTaskType: sif.CollectTaskType,\n\t\tDo: func(d sif.DataFrame) (*sif.DataFrameOperationResult, error) {\n\t\t\tif d.GetDataSource().IsStreaming() {\n\t\t\t\treturn nil, fmt.Errorf(\"cannot collect() from a streaming DataSource\")\n\t\t\t}\n\t\t\treturn &sif.DataFrameOperationResult{\n\t\t\t\tTask: &collectTask{collectionLimit: collectionLimit},\n\t\t\t\tDataSchema: d.GetSchema().Clone(),\n\t\t\t}, nil\n\t\t},\n\t}\n}", "func (t *Tracer) newSpan() *Span {\n\treturn t.spanAllocator.Get()\n}", "func (tr *tracer) newRecordingSpan(psc, sc trace.SpanContext, name string, sr SamplingResult, config *trace.SpanConfig) *recordingSpan {\n\tstartTime := config.Timestamp()\n\tif startTime.IsZero() {\n\t\tstartTime = time.Now()\n\t}\n\n\ts := &recordingSpan{\n\t\t// Do not pre-allocate the attributes slice here! Doing so will\n\t\t// allocate memory that is likely never going to be used, or if used,\n\t\t// will be over-sized. The default Go compiler has been tested to\n\t\t// dynamically allocate needed space very well. Benchmarking has shown\n\t\t// it to be more performant than what we can predetermine here,\n\t\t// especially for the common use case of few to no added\n\t\t// attributes.\n\n\t\tparent: psc,\n\t\tspanContext: sc,\n\t\tspanKind: trace.ValidateSpanKind(config.SpanKind()),\n\t\tname: name,\n\t\tstartTime: startTime,\n\t\tevents: newEvictedQueue(tr.provider.spanLimits.EventCountLimit),\n\t\tlinks: newEvictedQueue(tr.provider.spanLimits.LinkCountLimit),\n\t\ttracer: tr,\n\t}\n\n\tfor _, l := range config.Links() {\n\t\ts.addLink(l)\n\t}\n\n\ts.SetAttributes(sr.Attributes...)\n\ts.SetAttributes(config.Attributes()...)\n\n\treturn s\n}", "func NewPacket(opcode byte, payload []byte) *Packet {\n\treturn &Packet{opcode, payload, false, 0, 0, 0}\n}", "func NewPacket(payloadtype uint8,\n\tpayloaddata []byte,\n\tseqnr uint16,\n\ttimestamp uint32,\n\tssrc uint32,\n\tgotmarker bool,\n\tnumcsrcs uint8,\n\tcsrcs []uint32,\n\tgotextension bool,\n\textensionid uint16,\n\textensionlen uint16,\n\textensiondata []uint32) *RTPPacket {\n\tthis := &RTPPacket{}\n\n\tthis.receivetime = &RTPTime{0, 0}\n\tif err := this.BuildPacket(payloadtype,\n\t\tpayloaddata,\n\t\tseqnr,\n\t\ttimestamp,\n\t\tssrc,\n\t\tgotmarker,\n\t\tnumcsrcs,\n\t\tcsrcs,\n\t\tgotextension,\n\t\textensionid,\n\t\textensionlen,\n\t\textensiondata); err != nil {\n\t\treturn nil\n\t}\n\n\treturn this\n}", "func NewCollector(config *CollectorConfig) (Collector, error) {\n\tc := &standardCollector{\n\t\trunning: true,\n\t\tevents: make(chan Event, config.EventBufferSize),\n\t\tconfig: config,\n\t\tneighbors: make(map[string]neighbor),\n\t\tRWMutex: &sync.RWMutex{},\n\t}\n\n\treturn c, nil\n}", "func (s *Slave) newPacket(q Query) (pp *BinaryPacket, err error) {\n\tpp = packetPool.GetWithID(s.c.nextID())\n\tif err = pp.packMsg(q, s.c.packData); err != nil {\n\t\ts.c.releasePacket(pp)\n\t\treturn nil, err\n\t}\n\treturn\n}", "func NewCollector(bindIP, port string) (*SyslogCollector, error) {\n\tdefer TRA(CE())\n\tchannel := make(syslog.LogPartsChannel)\n\tsysServ := syslog.NewServer()\n\tsysServ.SetHandler(syslog.NewChannelHandler(channel))\n\t// uses RFC3164 because it is default for rsyslog\n\tsysServ.SetFormat(syslog.RFC3164)\n\terr := sysServ.ListenUDP(fmt.Sprintf(\"%s:%s\", bindIP, port))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgo func(channel syslog.LogPartsChannel) {\n\t\tfor logEntry := range channel {\n\t\t\tinfo, err := ctl.NewHostInfo()\n\t\t\tif err != nil {\n\t\t\t\tinfo = &ctl.HostInfo{}\n\t\t\t}\n\t\t\tevent, err := ctl.NewEvent(logEntry, *info)\n\t\t\tif err != nil {\n\t\t\t\tErrorLogger.Printf(\"cannot format syslog entry: %s\\n\", err)\n\t\t\t}\n\t\t\terr = event.Save(SubmitPath())\n\t\t\tif err != nil {\n\t\t\t\tErrorLogger.Printf(\"cannot save syslog entry to file: %s\\n\", err)\n\t\t\t}\n\t\t}\n\t}(channel)\n\treturn &SyslogCollector{\n\t\tserver: sysServ,\n\t\tport: port,\n\t}, nil\n}", "func NewPacket(data []byte, code byte, length int) (p *Packet) {\n\tp = &Packet{\n\t\tData: data,\n\t\tCode: code,\n\t\tLength: length,\n\t}\n\treturn p\n}", "func NewCollectServer(cfg *ServerConfig) *CollectServer {\n\tserver := &CollectServer{Config: cfg}\n\tlogger := logrus.New()\n\tlogger.Out = cfg.LogCfg.Output\n\tlogger.Level = cfg.LogCfg.Level\n\tlogger.Formatter = cfg.LogCfg.Format\n\tserver.Logger = logger\n\treturn server\n}", "func NewPacket(fields ...Field) (*Packet, error) {\n\tp := &Packet{b: make([]byte, 0, MaxEIRPacketLength)}\n\tfor _, f := range fields {\n\t\tif err := f(p); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn p, nil\n}", "func NewCollection(label string) *Collection {\n\treturn &Collection{\n\t\tItems: make(map[string]*APIResource),\n\t\tmanifests: make(map[string][]byte),\n\t\tResourceLabel: label,\n\t}\n}", "func makePacket(addr string, args []string) Packet {\n\tmsg := NewMessage(addr)\n\tfor _, arg := range args {\n\t\tmsg.Append(arg)\n\t}\n\treturn msg\n}", "func newSpanProcessor(config Config) (*spanProcessor, error) {\n\tskipExpr, err := filterspan.NewSkipExpr(&config.MatchConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsp := &spanProcessor{\n\t\tconfig: config,\n\t\tskipExpr: skipExpr,\n\t}\n\n\t// Compile ToAttributes regexp and extract attributes names.\n\tif config.Rename.ToAttributes != nil {\n\t\tfor _, pattern := range config.Rename.ToAttributes.Rules {\n\t\t\tre, err := regexp.Compile(pattern)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"invalid regexp pattern %s\", pattern)\n\t\t\t}\n\n\t\t\trule := toAttributeRule{\n\t\t\t\tre: re,\n\t\t\t\t// Subexpression names will become attribute names during extraction.\n\t\t\t\tattrNames: re.SubexpNames(),\n\t\t\t}\n\n\t\t\tsp.toAttributeRules = append(sp.toAttributeRules, rule)\n\t\t}\n\t}\n\n\treturn sp, nil\n}", "func (p *Packet) AvNewPacket(s int) int {\n\treturn int(C.av_new_packet((*C.struct_AVPacket)(p), C.int(s)))\n}", "func NewCollector(config *Config) (coll *Collector, err error) {\n\tvar gelfWriter *gelf.Writer\n\n\tif gelfWriter, err = gelf.NewWriter(config.Graylog.Address); err != nil {\n\t\treturn nil, err\n\t}\n\n\tcoll = new(Collector)\n\tcoll.writer = gelfWriter\n\tcoll.host = config.Collector.Hostname\n\n\treturn coll, nil\n}", "func NewVpcCollector(logger log.Logger) (Collector, error) {\n\treturn &vpcCollector{\n\t\tdesc: vpcDesc,\n\t\tlogger: logger,\n\t}, nil\n}", "func (m *MessageProcessor) Collect(srcPeerID string, packet []byte, respRingBuf *ring.Buffer, services protocol.ServiceFlag, metadata *message.Metadata) ([]bytes.Buffer, error) {\n\tif len(packet) == 0 {\n\t\treturn nil, errors.New(\"empty packet provided\")\n\t}\n\tdefer m.trace(\"collected\", srcPeerID, time.Now().UnixNano(), packet)\n\n\tb := bytes.NewBuffer(packet)\n\ttopic := topics.Topic(b.Bytes()[0])\n\n\tmsg, err := message.Unmarshal(b, metadata)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error while unmarshaling: %s - topic: %s\", err, topic)\n\t}\n\n\treturn m.process(srcPeerID, msg, respRingBuf, services)\n}", "func newPoolCollector(config monitoring.MetricsConfig, logger *zap.Logger,\n\tspectrumClient spectrumservice.Client) (Collector, error) {\n\n\tlabelPool := []string{\"pool_name\", \"storage_system\"}\n\n\tproperties := make(map[string]*prometheus.Desc)\n\n\tfor _, p := range config.Metrics.Pools.Properties {\n\t\tproperties[p.PropertyName] = prometheus.NewDesc(p.PrometheusName, p.PrometheusHelp, labelPool, nil)\n\t}\n\n\treturn &poolCollector{\n\t\tibmSpectrumClient: spectrumClient,\n\t\tlogger: logger.Sugar(),\n\t\tproperties: properties,\n\t}, nil\n}", "func New(client *statsd.Client, interval time.Duration) *Collector {\n\treturn &Collector{\n\t\tinterval: interval,\n\t\tclient: client,\n\t\tdone: make(chan struct{}),\n\t}\n}", "func New(config Config) (*Collector, error) {\n\tif config.Logger == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"%T.Logger must not be empty\", config)\n\t}\n\n\tif config.IFace == \"\" {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"%T.IFace must not be empty\", config)\n\t}\n\n\tcollector := &Collector{\n\t\tiface: config.IFace,\n\t}\n\n\tnicStats, err := ethtool.Stats(collector.iface)\n\tif err != nil {\n\t\treturn nil, microerror.Mask(err)\n\t}\n\n\tcollector.metrics = make(map[string]*prometheus.Desc)\n\tfor label, _ := range nicStats {\n\t\tfqName := prometheus.BuildFQName(nic_metric_namespace, \"\", label)\n\t\tcollector.metrics[label] = prometheus.NewDesc(fqName, fmt.Sprintf(\"Generated description for metric %#q\", label), []string{\"iface\"}, nil)\n\t}\n\n\treturn collector, nil\n}", "func newCollection(d driver.Collection) *Collection {\n\treturn &Collection{driver: d}\n}", "func newSpanParser(src []byte) *spanParser {\n\tp := &parser{\n\t\tsrc: src,\n\t}\n\tsp := &spanParser{parser: p, ref: make(map[string]*reference), spanChan: make(chan Span)}\n\tgo sp.run()\n\treturn sp\n}", "func New() servicespec.LayerCollection {\n\treturn &collection{}\n}", "func NewPacket(code, identifier uint8, data []byte, additionalCapacity ...uint) Packet {\n\tl := len(data) + EapHeaderLen\n\tpacketCap := l\n\tif len(additionalCapacity) > 0 && l < int(EapMaxLen) {\n\t\tac := additionalCapacity[0]\n\t\tpacketCap = l + int(ac)\n\t\tif packetCap > int(EapMaxLen) {\n\t\t\tpacketCap = int(EapMaxLen)\n\t\t}\n\t}\n\tp := make([]byte, EapHeaderLen, packetCap)\n\tif l > EapHeaderLen {\n\t\tp = append(p, data...)\n\t}\n\tp[EapMsgCode], p[EapMsgIdentifier], p[EapMsgLenLow], p[EapMsgLenHigh] = code, identifier, uint8(l), uint8(l>>8)\n\treturn p\n}", "func NewCollector(client *api.Client, collectSnaphots, collectNetwork bool) prometheus.Collector {\n\treturn &VMCollector{client: client, collectSnapshots: collectSnaphots, collectNetwork: collectNetwork}\n}", "func coveringFromSpans(spans []roachpb.Span, payload interface{}) intervalccl.Covering {\n\tvar covering intervalccl.Covering\n\tfor _, span := range spans {\n\t\tcovering = append(covering, intervalccl.Range{\n\t\t\tStart: []byte(span.Key),\n\t\t\tEnd: []byte(span.EndKey),\n\t\t\tPayload: payload,\n\t\t})\n\t}\n\treturn covering\n}", "func NewCollector(logicalSystem string) collector.RPCCollector {\n\treturn &bgpCollector{LogicalSystem: logicalSystem}\n}", "func (m *SpanManager) NewSpanFromRequest(name string, req Request) *Span {\n\tif req.Sampled != nil && !*req.Sampled {\n\t\treturn NewDisabledTrace()\n\t}\n\n\tflags := int64(0)\n\tif req.Flags != nil {\n\t\tflags = *req.Flags\n\t}\n\n\tif req.TraceId == nil || req.SpanId == nil {\n\t\tif req.Sampled != nil {\n\t\t\treturn m.NewSampledTrace(name, flags&1 > 0)\n\t\t}\n\t\treturn m.NewTrace(name)\n\t}\n\n\treturn &Span{\n\t\tdata: zipkin.Span{\n\t\t\tTraceId: *req.TraceId,\n\t\t\tName: name,\n\t\t\tId: *req.SpanId,\n\t\t\tParentId: req.ParentId,\n\t\t\tDebug: flags&1 > 0},\n\t\tserver: true,\n\t\tmanager: m}\n}", "func NewSpan(name string, linked ...*Span) (*Span, FinishFunc) {\n\tspan := &Span{\n\t\tID: client.NewSpan(nil),\n\t\tAnnotations: make(map[string][]byte),\n\t}\n\tstart := time.Now()\n\tfn := func() error {\n\t\treturn client.Finish(span.ID, name, spanIDs(linked), span.Annotations, start, time.Now())\n\t}\n\treturn span, fn\n}", "func (collector *Collector) Collect(ch chan<- prometheus.Metric) {\n\tch <- prometheus.MustNewConstMetric(collector.incidentsCreatedCount, prometheus.CounterValue, collector.storage.GetIncidentsCreatedCount())\n}", "func (s StructuredSyslog) New() cue.Collector {\n\tif s.App == \"\" {\n\t\tlog.Warn(\"StructuredSyslog.New called to created a collector, but App param is empty. Returning nil collector.\")\n\t\treturn nil\n\t}\n\n\tvar err error\n\tif s.Network == \"\" || s.Address == \"\" {\n\t\ts.Network, s.Address, err = localSyslog()\n\t}\n\tif err != nil {\n\t\tlog.Warn(\"StructuredSyslog.New called to created a collector, but Network or Address param is empty. Couldn't find a local syslog socket either. Returning nil collector.\")\n\t\treturn nil\n\t}\n\n\treturn &structuredCollector{\n\t\tStructuredSyslog: s,\n\t\tsocket: Socket{\n\t\t\tFormatter: structuredFormatter(s.Facility, s.App, s.MessageFormatter, s.StructuredFormatter, s.ID, s.WriteBOM),\n\t\t\tNetwork: s.Network,\n\t\t\tAddress: s.Address,\n\t\t\tTLS: s.TLS,\n\t\t}.New(),\n\t}\n}", "func NewCollector(l *logrus.Entry, updateInterval time.Duration) *Collector {\n\tcol := &Collector{\n\t\tMsgEvtChan: make(chan *discordgo.Message, 1000),\n\t\tinterval: updateInterval,\n\t\tl: l,\n\t\tchannels: make(map[int64]*entry),\n\t}\n\n\tgo col.run()\n\n\treturn col\n}", "func (t *TraceWrapper) newSpan(name string) *SpanWrapper {\n\tctx := t.ctx\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\n\ts, ok := ctx.Value(spanKey{}).(*SpanWrapper)\n\tif !ok {\n\t\ts = t.generateSpan(name)\n\t\tctx = context.WithValue(ctx, spanKey{}, s)\n\t\ts.ctx, t.ctx = ctx, ctx\n\t}\n\treturn s\n}", "func (c *libbeatCollector) Collect(ch chan<- prometheus.Metric) {\n\n\tfor _, i := range c.metrics {\n\t\tch <- prometheus.MustNewConstMetric(i.desc, i.valType, i.eval(c.stats))\n\t}\n\n\t// output.type with dynamic label\n\tch <- prometheus.MustNewConstMetric(libbeatOutputType, prometheus.CounterValue, float64(1), c.stats.LibBeat.Output.Type)\n\n}", "func NewCollector(store *store.MemoryStore) *Collector {\n\treturn &Collector{\n\t\tstore: store,\n\t\tstopChan: make(chan struct{}),\n\t\tdoneChan: make(chan struct{}),\n\t}\n}", "func NewPacketCapture() *PacketCapture {\n\treturn &PacketCapture{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: KindPacketCapture,\n\t\t\tAPIVersion: GroupVersionCurrent,\n\t\t},\n\t}\n}", "func NewCollection(context, id string, members interface{}) *CollectionResource {\n\treturn &CollectionResource{\n\t\tResource: Resource{\n\t\t\tContext: context,\n\t\t\tNodeID: id,\n\t\t\tType: \"Collection\",\n\t\t},\n\t\tMembers: members,\n\t}\n}", "func newUnidataCollector(udtbin string) *unidataCollector {\n\treturn &unidataCollector{\n\t\tudtBinPath: udtbin,\n\t\tlicenseUsage: prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(namespace, \"license\", \"usage\"),\n\t\t\t\"Unidata license usage.\",\n\t\t\t[]string{\"model\", \"src\"},\n\t\t\tnil,\n\t\t),\n\t\tlicenseLimit: prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(namespace, \"license\", \"limit\"),\n\t\t\t\"Unidata license limits.\",\n\t\t\t[]string{\"model\"},\n\t\t\tnil,\n\t\t),\n\t\tup: prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(namespace, \"\", \"up\"),\n\t\t\t\"Unidata exporter success.\",\n\t\t\tnil, nil,\n\t\t),\n\t}\n}", "func New(cfg Collector, nodeInfo collectors.NodeInfo, rels *ContainerTaskRels) (Collector, chan producers.MetricsMessage) {\n\tc := cfg\n\tc.log = logrus.WithFields(logrus.Fields{\"collector\": \"mesos-agent\"})\n\tc.nodeInfo = nodeInfo\n\tc.metricsChan = make(chan producers.MetricsMessage)\n\tc.ContainerTaskRels = rels\n\treturn c, c.metricsChan\n}", "func newCollectOptions() *common.CollectOptions {\n\topts := &common.CollectOptions{}\n\n\topts.Config = common.EdgecoreConfigPath\n\topts.OutputPath = \".\"\n\topts.Detail = false\n\treturn opts\n}", "func NewSpan(tracer *Tracing, name string) Span {\n\treturn newSpanWithStart(tracer, name, time.Now())\n}", "func (tlc *TLCMessage) CreatePacket() *GossipPacket {\n\treturn &GossipPacket{\n\t\tTLCMessage: tlc,\n\t}\n}", "func spanToRequestData(span *tracepb.Span) *contracts.RequestData {\n\t/*\n\t\tRequest type comes from a few attributes.\n\n\t\tHTTP\n\t\thttps://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/data-http.md\n\n\t\tRPC (gRPC)\n\t\thttps://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/data-rpc.md\n\n\t\tDatabase\n\t\thttps://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/data-database.md\n\t*/\n\n\t// https://github.com/microsoft/ApplicationInsights-Go/blob/master/appinsights/contracts/requestdata.go\n\t// Start with some reasonable default for server spans.\n\tdata := contracts.NewRequestData()\n\tdata.Id = idToHex(span.SpanId)\n\tdata.Name = span.Name.Value\n\tdata.Duration = formatSpanDuration(span)\n\tdata.Properties = make(map[string]string)\n\tdata.Measurements = make(map[string]float64)\n\tdata.ResponseCode = \"0\"\n\tdata.Success = true\n\n\tif span.Attributes != nil && span.Attributes.AttributeMap != nil {\n\t\tattributes := span.Attributes.AttributeMap\n\t\tcomponent := \"\"\n\t\tonAttributeStringValueExists(attributes, spanAttributeKeyComponent, func(val string) { component = val })\n\n\t\t// TODO remove this once the OpenTelemetry wire format protocol is adopted.\n\t\t// The specs indicate that component is a required tag\n\t\tonAttributeStringValueExists(attributes, spanAttributeKeyHTTPMethod, func(val string) { component = \"http\" })\n\n\t\tswitch component {\n\t\tcase \"\":\n\t\t\tfillRequestDataInternal(span, data)\n\t\tcase \"http\":\n\t\t\tfillRequestDataHTTP(span, data)\n\t\tcase \"grpc\":\n\t\t\tfillRequestDataGrpc(span, data)\n\t\tdefault:\n\t\t}\n\t}\n\n\treturn data\n}", "func (tb *Batch) newChildSpan(ctx context.Context) ddtrace.Span {\n\tp := tb.params\n\topts := []ddtrace.StartSpanOption{\n\t\ttracer.SpanType(ext.SpanTypeCassandra),\n\t\ttracer.ServiceName(p.config.serviceName),\n\t\ttracer.ResourceName(p.config.resourceName),\n\t\ttracer.Tag(ext.CassandraConsistencyLevel, tb.Cons.String()),\n\t\ttracer.Tag(ext.CassandraKeyspace, tb.Keyspace()),\n\t\ttracer.Tag(ext.Component, componentName),\n\t\ttracer.Tag(ext.SpanKind, ext.SpanKindClient),\n\t\ttracer.Tag(ext.DBSystem, ext.DBSystemCassandra),\n\t}\n\tif !math.IsNaN(p.config.analyticsRate) {\n\t\topts = append(opts, tracer.Tag(ext.EventSampleRate, p.config.analyticsRate))\n\t}\n\tif tb.clusterContactPoints != \"\" {\n\t\topts = append(opts, tracer.Tag(ext.CassandraContactPoints, tb.clusterContactPoints))\n\t}\n\tfor k, v := range tb.config.customTags {\n\t\topts = append(opts, tracer.Tag(k, v))\n\t}\n\tspan, _ := tracer.StartSpanFromContext(ctx, p.config.batchSpanName, opts...)\n\treturn span\n}", "func (t *Trace) NewSpan(name string) platform.Span {\n\ts := NewSpan(name).(*Span)\n\ts.logger = t.logger\n\treturn s\n}", "func newWarnEvent(pkg *pkg) (*WarnEvent, error) {\n\tvar result WarnEvent\n\terr := msgpack.Unmarshal(pkg.data, &result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &result, nil\n}", "func newInstrumentationStmt(funcIdent string, args []dst.Expr) dst.Stmt {\n\treturn &dst.BlockStmt{\n\t\tList: []dst.Stmt{\n\t\t\t&dst.ExprStmt{\n\t\t\t\tX: &dst.CallExpr{\n\t\t\t\t\tFun: &dst.Ident{\n\t\t\t\t\t\tName: funcIdent,\n\t\t\t\t\t},\n\t\t\t\t\tArgs: args,\n\t\t\t\t\tEllipsis: false,\n\t\t\t\t\tDecs: dst.CallExprDecorations{},\n\t\t\t\t},\n\t\t\t\tDecs: dst.ExprStmtDecorations{},\n\t\t\t},\n\t\t},\n\t}\n}", "func (c *cluster) collectSpans(\n\tt *testing.T, txn *roachpb.Transaction, ts hlc.Timestamp, reqs []roachpb.Request,\n) (latchSpans, lockSpans *spanset.SpanSet) {\n\tlatchSpans, lockSpans = &spanset.SpanSet{}, &spanset.SpanSet{}\n\th := roachpb.Header{Txn: txn, Timestamp: ts}\n\tfor _, req := range reqs {\n\t\tif cmd, ok := batcheval.LookupCommand(req.Method()); ok {\n\t\t\tcmd.DeclareKeys(c.rangeDesc, h, req, latchSpans, lockSpans)\n\t\t} else {\n\t\t\tt.Fatalf(\"unrecognized command %s\", req.Method())\n\t\t}\n\t}\n\n\t// Commands may create a large number of duplicate spans. De-duplicate\n\t// them to reduce the number of spans we pass to the spanlatch manager.\n\tfor _, s := range [...]*spanset.SpanSet{latchSpans, lockSpans} {\n\t\ts.SortAndDedup()\n\t\tif err := s.Validate(); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n\treturn latchSpans, lockSpans\n}", "func NewCollector(api API) *Collector {\n\treturn &Collector{api: api}\n}", "func collectJoinRequestPacket(ctx common.Context, rxPacket gw.RXPacket) error {\n\treturn collectAndCallOnce(ctx.RedisPool, rxPacket, func(rxPacket models.RXPacket) error {\n\t\treturn handleCollectedJoinRequestPackets(ctx, rxPacket)\n\t})\n}", "func NewRawPacket(bytes ...[]byte) (*Packet, error) {\n\t//concatenate\n\tb := make([]byte, 0, MaxEIRPacketLength)\n\tfor _, bb := range bytes {\n\t\tb = append(b, bb...)\n\t}\n\n\t//decode the bytes\n\tm, err := parser.Parse(b)\n\tif err != nil {\n\t\tif !errors.Is(err, parser.EmptyOrNilPdu) {\n\t\t\terr = fmt.Errorf(\"pdu decode: %w\", err)\n\t\t} else {\n\t\t\terr = nil\n\t\t}\n\t}\n\n\tswitch {\n\tcase err == nil:\n\t\t// ok\n\tcase len(m) > 0:\n\t\t// some of the adv was ok, append the error\n\t\tm[ble.AdvertisementMapKeys.AdvertisementError] = err.Error()\n\tdefault:\n\t\t// nothing was ok parsed, exit\n\t\treturn nil, err\n\t}\n\n\tp := &Packet{b: b, m: m}\n\treturn p, nil\n}", "func NewCollector() Collector {\n\treturn make(Collector)\n}", "func NewCollector() *Collector {\n\twg := &sync.WaitGroup{}\n\tevtCh := make(chan *eventsapi.ClientEvent, collChanBufferSize)\n\n\tc := &Collector{&atomic.Value{}, wg, evtCh}\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\n\t\tvar events []*eventsapi.ClientEvent\n\t\tfor evt := range evtCh {\n\t\t\tevents = append(events, evt)\n\t\t}\n\n\t\tc.val.Store(events)\n\t}()\n\n\treturn c\n}", "func NewSpan() Span {\n\treturn newSpan(&otlptrace.Span{})\n}", "func newBatch(evts []*evtsapi.Event, offset *events.Offset) (events.Batch, error) {\n\tif offset == nil {\n\t\treturn nil, fmt.Errorf(\"cannot create a batch with nil offset\")\n\t}\n\treturn &batch{evts: evts, offset: offset}, nil\n}", "func (e *ebpfConntracker) Collect(ch chan<- prometheus.Metric) {\n\tebpfTelemetry := &netebpf.ConntrackTelemetry{}\n\tif err := e.telemetryMap.Lookup(unsafe.Pointer(&zero), unsafe.Pointer(ebpfTelemetry)); err != nil {\n\t\tlog.Tracef(\"error retrieving the telemetry struct: %s\", err)\n\t} else {\n\t\tdelta := ebpfTelemetry.Registers - conntrackerTelemetry.lastRegisters\n\t\tconntrackerTelemetry.lastRegisters = ebpfTelemetry.Registers\n\t\tch <- prometheus.MustNewConstMetric(conntrackerTelemetry.registersTotal, prometheus.CounterValue, float64(delta))\n\t}\n}", "func newNetBufPayload(data []byte) (*netBuf, []byte) {\n\tnb := &netBuf{\n\t\tbuf: data,\n\t\tpool: -1,\n\t}\n\treturn nb, nb.buf\n}", "func (tzGrpCol TimeZoneGroupCollection) New() TimeZoneGroupCollection {\n\tnewTzGrp := TimeZoneGroupCollection{}\n\n\tnewTzGrp.tzGroups = make([]TimeZoneGroupDto, 0, 300)\n\n\treturn newTzGrp\n}", "func NewPacketParser(source string, dst chan<- *Message) *PacketParser {\n\tpp := &PacketParser{\n\t\tasync: make(chan sendSentence, 200),\n\t\tsourceName: source,\n\t}\n\tgo pp.decodeSentences(dst)\n\treturn pp\n}", "func (c *HTTPCollector) createBuffer() []*zipkincore.Span {\n\treturn c.batchPool.Get().([]*zipkincore.Span)\n}", "func NewCollector() Collector {\n\treturn Collector{client: NewClient(time.Second * 5)}\n}", "func (l *listener) newPacketConn(raddr net.Addr) *PacketConn {\n\treturn &PacketConn{\n\t\tlistener: l,\n\t\traddr: raddr,\n\t\tbuffer: idtlsnet.NewPacketBuffer(),\n\t\tdoneCh: make(chan struct{}),\n\t\twriteDeadline: deadline.New(),\n\t}\n}", "func (network *Network) CreatePacket(rpc string, sourceip string, sourceid string, targetid string, contacts []Contact, value []byte) *packet {\n\tcreatedPacket := &packet{\n\t\tRPC: rpc,\n\t\tSourceID: sourceid,\n\t\tSourceIP: sourceip,\n\t\tTargetID: targetid,\n\t\tContacts: contacts,\n\t\tValue: value,\n\t}\n\treturn createdPacket\n}", "func (s ProxyClaimRequestRequest) NewLabel() (util.LocalizedText, error) {\n\tss, err := util.NewLocalizedText(s.Struct.Segment())\n\tif err != nil {\n\t\treturn util.LocalizedText{}, err\n\t}\n\terr = s.Struct.SetPtr(2, ss.Struct.ToPtr())\n\treturn ss, err\n}", "func (m *MeterImpl) collect(ctx context.Context, labels []attribute.KeyValue, measurements []Measurement) {\n\tm.provider.addMeasurement(Batch{\n\t\tCtx: ctx,\n\t\tLabels: labels,\n\t\tMeasurements: measurements,\n\t\tLibrary: m.library,\n\t})\n}", "func (tr *tracer) newSpan(ctx context.Context, name string, config *trace.SpanConfig) trace.Span {\n\t// If told explicitly to make this a new root use a zero value SpanContext\n\t// as a parent which contains an invalid trace ID and is not remote.\n\tvar psc trace.SpanContext\n\tif config.NewRoot() {\n\t\tctx = trace.ContextWithSpanContext(ctx, psc)\n\t} else {\n\t\tpsc = trace.SpanContextFromContext(ctx)\n\t}\n\n\t// If there is a valid parent trace ID, use it to ensure the continuity of\n\t// the trace. Always generate a new span ID so other components can rely\n\t// on a unique span ID, even if the Span is non-recording.\n\tvar tid trace.TraceID\n\tvar sid trace.SpanID\n\tif !psc.TraceID().IsValid() {\n\t\ttid, sid = tr.provider.idGenerator.NewIDs(ctx)\n\t} else {\n\t\ttid = psc.TraceID()\n\t\tsid = tr.provider.idGenerator.NewSpanID(ctx, tid)\n\t}\n\n\tsamplingResult := tr.provider.sampler.ShouldSample(SamplingParameters{\n\t\tParentContext: ctx,\n\t\tTraceID: tid,\n\t\tName: name,\n\t\tKind: config.SpanKind(),\n\t\tAttributes: config.Attributes(),\n\t\tLinks: config.Links(),\n\t})\n\n\tscc := trace.SpanContextConfig{\n\t\tTraceID: tid,\n\t\tSpanID: sid,\n\t\tTraceState: samplingResult.Tracestate,\n\t}\n\tif isSampled(samplingResult) {\n\t\tscc.TraceFlags = psc.TraceFlags() | trace.FlagsSampled\n\t} else {\n\t\tscc.TraceFlags = psc.TraceFlags() &^ trace.FlagsSampled\n\t}\n\tsc := trace.NewSpanContext(scc)\n\n\tif !isRecording(samplingResult) {\n\t\treturn tr.newNonRecordingSpan(sc)\n\t}\n\treturn tr.newRecordingSpan(psc, sc, name, samplingResult, config)\n}", "func NewPBPacket(id ProtoID) interface{} {\n packet, ok := packetMap[id];\n if !ok {\n return nil;\n }\n ms, _ := packet.(proto.Message);\n \n return proto.Clone(ms)\n}", "func MakePacket(args ...interface{}) (pkt *pktmbuf.Packet) {\n\tvar mp *pktmbuf.Pool\n\tvar segments [][]byte\n\tvar headroom *Headroom\n\tfor i, arg := range args {\n\t\tswitch a := arg.(type) {\n\t\tcase []byte:\n\t\t\tsegments = append(segments, a)\n\t\tcase string:\n\t\t\tsegments = append(segments, BytesFromHex(a))\n\t\tcase []string:\n\t\t\tfor _, hexString := range a {\n\t\t\t\tsegments = append(segments, BytesFromHex(hexString))\n\t\t\t}\n\t\tcase *pktmbuf.Pool:\n\t\t\tmp = a\n\t\tcase Headroom:\n\t\t\theadroom = &a\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"MakePacket args[%d] invalid type %T\", i, arg))\n\t\t}\n\t}\n\n\tif mp == nil {\n\t\tmp = Direct.Pool()\n\t}\n\tif len(segments) == 0 {\n\t\treturn mp.MustAlloc(1)[0]\n\t}\n\n\tvec := mp.MustAlloc(len(segments))\n\tpkt = vec[0]\n\tfor i, b := range segments {\n\t\tseg := vec[i]\n\t\tif headroom != nil {\n\t\t\tseg.SetHeadroom(int(*headroom))\n\t\t}\n\t\tseg.Append(b)\n\t\tif i > 0 {\n\t\t\tpkt.Chain(seg)\n\t\t}\n\t}\n\treturn pkt\n}", "func (x *fastReflection_MsgCommunityPoolSpend) New() protoreflect.Message {\n\treturn new(fastReflection_MsgCommunityPoolSpend)\n}", "func (as *AggregateStore) Collect(id SpanID, anns ...Annotation) error {\n\tas.mu.Lock()\n\tdefer as.mu.Unlock()\n\n\t// Initialization\n\tif as.groups == nil {\n\t\tas.groups = make(map[ID]*spanGroup)\n\t\tas.groupsByName = make(map[string]ID)\n\t\tas.pre = &LimitStore{\n\t\t\tMax: as.MaxRate,\n\t\t\tDeleteStore: NewMemoryStore(),\n\t\t}\n\t}\n\n\t// Collect into the limit store.\n\tif err := as.pre.Collect(id, anns...); err != nil {\n\t\treturn err\n\t}\n\n\t// Consider eviction of old data.\n\tif time.Since(as.lastEvicted) > as.MinEvictAge {\n\t\tif err := as.evictBefore(time.Now().Add(-1 * as.MinEvictAge)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Grab the group for our span.\n\tgroup, ok := as.group(id, anns...)\n\tif !ok {\n\t\t// We don't have a group for the trace, and can't create one (the\n\t\t// spanName event isn't present yet).\n\t\treturn nil\n\t}\n\n\t// Unmarshal the events.\n\tvar events []Event\n\tif err := UnmarshalEvents(anns, &events); err != nil {\n\t\treturn err\n\t}\n\n\t// Find the start and end time of the trace.\n\teStart, eEnd, ok := findTraceTimes(events)\n\tif !ok {\n\t\t// We didn't find any timespan events at all, so we're done here.\n\t\treturn nil\n\t}\n\n\t// Update the group to consider this trace being one of the slowest.\n\tgroup.update(eStart, eEnd, id.Trace, func(trace ID) {\n\t\t// Delete the request trace from the output store.\n\t\tif err := as.deleteOutput(trace); err != nil {\n\t\t\tlog.Printf(\"AggregateStore: failed to delete a trace: %s\", err)\n\t\t}\n\t})\n\n\t// Move traces from the limit store into the group, as needed.\n\tfor _, slowest := range group.Slowest {\n\t\t// Find the trace in the limit store.\n\t\ttrace, err := as.pre.Trace(slowest.TraceID)\n\t\tif err == ErrTraceNotFound {\n\t\t\tcontinue\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Place into output store.\n\t\tvar walk func(t *Trace) error\n\t\twalk = func(t *Trace) error {\n\t\t\terr := as.MemoryStore.Collect(t.Span.ID, t.Span.Annotations...)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfor _, sub := range t.Sub {\n\t\t\t\tif err := walk(sub); 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\tif err := walk(trace); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Delete from the limit store.\n\t\terr = as.pre.Delete(slowest.TraceID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Prepare the aggregation event (before locking below).\n\tev := &AggregateEvent{\n\t\tName: group.Name,\n\t\tTimes: group.Times,\n\t}\n\tfor _, slowest := range group.Slowest {\n\t\tif !slowest.empty() {\n\t\t\tev.Slowest = append(ev.Slowest, slowest.TraceID)\n\t\t}\n\t}\n\tif as.Debug && len(ev.Slowest) == 0 {\n\t\tlog.Printf(\"AggregateStore: no slowest traces for group %q (consider increasing MaxRate)\", group.Name)\n\t}\n\n\t// As we're updating the aggregation event, we go ahead and delete the old\n\t// one now. We do this all under as.MemoryStore.Lock otherwise users (e.g. the\n\t// web UI) can pull from as.MemoryStore when the trace has been deleted.\n\tas.MemoryStore.Lock()\n\tdefer as.MemoryStore.Unlock()\n\tif err := as.MemoryStore.deleteNoLock(group.Trace); err != nil {\n\t\treturn err\n\t}\n\n\t// Record an aggregate event with the given name.\n\trecEvent := func(e Event) error {\n\t\tanns, err := MarshalEvent(e)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn as.MemoryStore.collectNoLock(SpanID{Trace: group.Trace}, anns...)\n\t}\n\tif err := recEvent(spanName{Name: group.Name}); err != nil {\n\t\treturn err\n\t}\n\tif err := recEvent(ev); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *bgpCollector) Collect(client collector.Client, ch chan<- prometheus.Metric, labelValues []string) error {\n\terr := c.collect(client, ch, labelValues)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (*latencyR) NewStruct() *latencyR {\n\treturn &latencyR{}\n}", "func NewIntervalOfSpan(l, s int64) Interval {\n\treturn NewInterval(l, l+s)\n}", "func New() *AllocGrp {\n\tvar m AllocGrp\n\treturn &m\n}", "func (bt *BlipTester) newRequest() *blip.Message {\n\tmsg := blip.NewRequest()\n\tbt.addCollectionProperty(msg)\n\treturn msg\n}", "func NewCollector(username string, token string, source string, timeout time.Duration, waitGroup *sync.WaitGroup) Collector {\n\treturn &collector{\n\t\turl: metricsEndpont,\n\t\tusername: username,\n\t\ttoken: token,\n\t\tsource: source,\n\t\ttimeout: timeout,\n\n\t\thttpClient: &http.Client{\n\t\t\tTimeout: time.Second * 30,\n\t\t},\n\t\twaitGroup: waitGroup,\n\t\tstop: make(chan bool),\n\t\tbuffer: make(chan gauge, 10000),\n\t}\n}", "func (s StaticInfoExtn) NewLatency() (StaticInfoExtn_LatencyInfo, error) {\n\tss, err := NewStaticInfoExtn_LatencyInfo(s.Struct.Segment())\n\tif err != nil {\n\t\treturn StaticInfoExtn_LatencyInfo{}, err\n\t}\n\terr = s.Struct.SetPtr(0, ss.Struct.ToPtr())\n\treturn ss, err\n}", "func NewCollection(address, database, collection string) *Collection {\n\treturn &Collection{address: address, database: database, collection: collection}\n}", "func newReceive(name string, channel string) *Instruction {\n\treturn &Instruction{\n\t\tType: ReceiveInst,\n\t\tName: name,\n\t\tChannel: channel,\n\t}\n}", "func NewSpanID(bytes [8]byte) SpanID {\n\treturn SpanID{id: bytes}\n}", "func NewInboundPacket(id int) (encoding.Codable, error) {\n\ttypePtr, ok := inboundTypes[id]\n\tif !ok {\n\t\treturn new(UnknownPacket), nil\n\t}\n\ttyp := reflect.TypeOf(typePtr).Elem()\n\tvalue := reflect.New(typ)\n\treturn value.Interface().(encoding.Codable), nil\n}", "func New(windowSizes []time.Duration, opts *Options) *Latency {\n\tprecision := time.Nanosecond\n\tif opts != nil && opts.AvgPrecision.Nanoseconds() != 0 {\n\t\tprecision = opts.AvgPrecision\n\t}\n\tsf := precision / time.Nanosecond\n\tcompute := func(ts, now time.Time) time.Duration { return now.Sub(ts) }\n\tif opts != nil && opts.ComputeFunc != nil {\n\t\tcompute = opts.ComputeFunc\n\t}\n\tvar windows []*window\n\tfor _, size := range windowSizes {\n\t\twindows = append(windows, newWindow(size, sf.Nanoseconds()))\n\t}\n\treturn &Latency{\n\t\twindows: windows,\n\t\tscaleFactor: sf,\n\t\tcompute: compute,\n\t}\n}", "func newConstProto() *Instruction {\n\treturn &Instruction{\n\t\tType: ConstProtoInst,\n\t\tName: \"ConstProto\",\n\t}\n}", "func (s Sentry) New() cue.Collector {\n\tif s.DSN == \"\" || !validDSN(s.DSN) {\n\t\tlog.Warn(\"Sentry.New called to created a collector, but DSN param is empty or invalid. Returning nil collector.\")\n\t\treturn nil\n\t}\n\treturn &sentryCollector{\n\t\tSentry: s,\n\t\thttp: collector.HTTP{RequestFormatter: s.formatRequest}.New(),\n\t}\n}", "func (ack *TLCAck) CreatePacket() *GossipPacket {\n\treturn &GossipPacket{\n\t\tAck: ack,\n\t}\n}", "func newSpanAttributesProcessor(logger *zap.Logger, attrProc *attraction.AttrProc, skipExpr expr.BoolExpr[ottlspan.TransformContext]) *spanAttributesProcessor {\n\treturn &spanAttributesProcessor{\n\t\tlogger: logger,\n\t\tattrProc: attrProc,\n\t\tskipExpr: skipExpr,\n\t}\n}" ]
[ "0.5870983", "0.58339983", "0.5465129", "0.54080963", "0.54068404", "0.53500813", "0.53196156", "0.5210788", "0.5104033", "0.50751895", "0.49993894", "0.4986562", "0.49562997", "0.4911006", "0.4851788", "0.48231903", "0.48181325", "0.48133972", "0.48114294", "0.47517624", "0.47467238", "0.4743829", "0.47375944", "0.47084537", "0.4707631", "0.46969658", "0.46923175", "0.46914193", "0.46682075", "0.46443638", "0.4633962", "0.4623287", "0.45992997", "0.4594009", "0.45838043", "0.45803794", "0.45680404", "0.45524016", "0.45436624", "0.45175812", "0.45163614", "0.45117244", "0.45016155", "0.4501398", "0.4493037", "0.4483515", "0.44824034", "0.44668302", "0.44659483", "0.44652095", "0.44533607", "0.4452926", "0.44507053", "0.44474384", "0.44462577", "0.44441465", "0.44342765", "0.44275355", "0.44259456", "0.4425517", "0.44192117", "0.4399811", "0.43899953", "0.43864053", "0.43819934", "0.43745235", "0.4373213", "0.43694702", "0.4362457", "0.43598878", "0.43593884", "0.43528998", "0.43470305", "0.43468", "0.43456158", "0.43426877", "0.43417785", "0.43322182", "0.43205276", "0.43205205", "0.431368", "0.4305334", "0.43044743", "0.43017903", "0.43014362", "0.4300798", "0.42864162", "0.4280633", "0.42793158", "0.4274801", "0.42676046", "0.42606062", "0.4257083", "0.42565346", "0.42514035", "0.42321303", "0.42296574", "0.4226948", "0.42167306", "0.4216077" ]
0.87639284
0
Collect adds the span and annotations to a local buffer until the next call to Flush (or when MinInterval elapses), at which point they are sent (grouped by span) to the underlying collector.
Collect добавляет спан и аннотации в локальный буфер до следующего вызова Flush (или при наступлении MinInterval), после чего они отправляются (сгруппированные по спанам) в нижележащий сборщик.
func (cc *ChunkedCollector) Collect(span SpanID, anns ...Annotation) error { cc.mu.Lock() defer cc.mu.Unlock() if cc.stopped { return errors.New("ChunkedCollector is stopped") } if !cc.started { cc.start() } if cc.pendingBySpanID == nil { cc.pendingBySpanID = map[SpanID]*wire.CollectPacket{} } if p, present := cc.pendingBySpanID[span]; present { if len(anns) > 0 { p.Annotation = append(p.Annotation, Annotations(anns).wire()...) } } else { cc.pendingBySpanID[span] = newCollectPacket(span, anns) cc.pending = append(cc.pending, span) } if err := cc.lastErr; err != nil { cc.lastErr = nil return err } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (as *AggregateStore) Collect(id SpanID, anns ...Annotation) error {\n\tas.mu.Lock()\n\tdefer as.mu.Unlock()\n\n\t// Initialization\n\tif as.groups == nil {\n\t\tas.groups = make(map[ID]*spanGroup)\n\t\tas.groupsByName = make(map[string]ID)\n\t\tas.pre = &LimitStore{\n\t\t\tMax: as.MaxRate,\n\t\t\tDeleteStore: NewMemoryStore(),\n\t\t}\n\t}\n\n\t// Collect into the limit store.\n\tif err := as.pre.Collect(id, anns...); err != nil {\n\t\treturn err\n\t}\n\n\t// Consider eviction of old data.\n\tif time.Since(as.lastEvicted) > as.MinEvictAge {\n\t\tif err := as.evictBefore(time.Now().Add(-1 * as.MinEvictAge)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Grab the group for our span.\n\tgroup, ok := as.group(id, anns...)\n\tif !ok {\n\t\t// We don't have a group for the trace, and can't create one (the\n\t\t// spanName event isn't present yet).\n\t\treturn nil\n\t}\n\n\t// Unmarshal the events.\n\tvar events []Event\n\tif err := UnmarshalEvents(anns, &events); err != nil {\n\t\treturn err\n\t}\n\n\t// Find the start and end time of the trace.\n\teStart, eEnd, ok := findTraceTimes(events)\n\tif !ok {\n\t\t// We didn't find any timespan events at all, so we're done here.\n\t\treturn nil\n\t}\n\n\t// Update the group to consider this trace being one of the slowest.\n\tgroup.update(eStart, eEnd, id.Trace, func(trace ID) {\n\t\t// Delete the request trace from the output store.\n\t\tif err := as.deleteOutput(trace); err != nil {\n\t\t\tlog.Printf(\"AggregateStore: failed to delete a trace: %s\", err)\n\t\t}\n\t})\n\n\t// Move traces from the limit store into the group, as needed.\n\tfor _, slowest := range group.Slowest {\n\t\t// Find the trace in the limit store.\n\t\ttrace, err := as.pre.Trace(slowest.TraceID)\n\t\tif err == ErrTraceNotFound {\n\t\t\tcontinue\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Place into output store.\n\t\tvar walk func(t *Trace) error\n\t\twalk = func(t *Trace) error {\n\t\t\terr := as.MemoryStore.Collect(t.Span.ID, t.Span.Annotations...)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfor _, sub := range t.Sub {\n\t\t\t\tif err := walk(sub); 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\tif err := walk(trace); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Delete from the limit store.\n\t\terr = as.pre.Delete(slowest.TraceID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Prepare the aggregation event (before locking below).\n\tev := &AggregateEvent{\n\t\tName: group.Name,\n\t\tTimes: group.Times,\n\t}\n\tfor _, slowest := range group.Slowest {\n\t\tif !slowest.empty() {\n\t\t\tev.Slowest = append(ev.Slowest, slowest.TraceID)\n\t\t}\n\t}\n\tif as.Debug && len(ev.Slowest) == 0 {\n\t\tlog.Printf(\"AggregateStore: no slowest traces for group %q (consider increasing MaxRate)\", group.Name)\n\t}\n\n\t// As we're updating the aggregation event, we go ahead and delete the old\n\t// one now. We do this all under as.MemoryStore.Lock otherwise users (e.g. the\n\t// web UI) can pull from as.MemoryStore when the trace has been deleted.\n\tas.MemoryStore.Lock()\n\tdefer as.MemoryStore.Unlock()\n\tif err := as.MemoryStore.deleteNoLock(group.Trace); err != nil {\n\t\treturn err\n\t}\n\n\t// Record an aggregate event with the given name.\n\trecEvent := func(e Event) error {\n\t\tanns, err := MarshalEvent(e)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn as.MemoryStore.collectNoLock(SpanID{Trace: group.Trace}, anns...)\n\t}\n\tif err := recEvent(spanName{Name: group.Name}); err != nil {\n\t\treturn err\n\t}\n\tif err := recEvent(ev); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (rc *RemoteCollector) Collect(span SpanID, anns ...Annotation) error {\n\treturn rc.collectAndRetry(newCollectPacket(span, anns))\n}", "func (w *Writer) Collect(ch chan<- prometheus.Metric) {\n\tw.kafkaWriteStatus.Collect(ch)\n\tw.queuedForWrites.Collect(ch)\n}", "func (l *LabelStatistics) Collect() {\n\tl.RLock()\n\tdefer l.RUnlock()\n\tfor level, count := range l.labelCounter {\n\t\tregionLabelLevelGauge.WithLabelValues(level).Set(float64(count))\n\t}\n}", "func (m httpReferenceDiscoveryMetrics) Collect(metrics chan<- prometheus.Metric) {\n\tm.firstPacket.Collect(metrics)\n\tm.totalTime.Collect(metrics)\n\tm.advertisedRefs.Collect(metrics)\n}", "func (m *MeterImpl) collect(ctx context.Context, labels []attribute.KeyValue, measurements []Measurement) {\n\tm.provider.addMeasurement(Batch{\n\t\tCtx: ctx,\n\t\tLabels: labels,\n\t\tMeasurements: measurements,\n\t\tLibrary: m.library,\n\t})\n}", "func (c *cluster) collectSpans(\n\tt *testing.T, txn *roachpb.Transaction, ts hlc.Timestamp, reqs []roachpb.Request,\n) (latchSpans, lockSpans *spanset.SpanSet) {\n\tlatchSpans, lockSpans = &spanset.SpanSet{}, &spanset.SpanSet{}\n\th := roachpb.Header{Txn: txn, Timestamp: ts}\n\tfor _, req := range reqs {\n\t\tif cmd, ok := batcheval.LookupCommand(req.Method()); ok {\n\t\t\tcmd.DeclareKeys(c.rangeDesc, h, req, latchSpans, lockSpans)\n\t\t} else {\n\t\t\tt.Fatalf(\"unrecognized command %s\", req.Method())\n\t\t}\n\t}\n\n\t// Commands may create a large number of duplicate spans. De-duplicate\n\t// them to reduce the number of spans we pass to the spanlatch manager.\n\tfor _, s := range [...]*spanset.SpanSet{latchSpans, lockSpans} {\n\t\ts.SortAndDedup()\n\t\tif err := s.Validate(); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n\treturn latchSpans, lockSpans\n}", "func (cc *ChunkedCollector) Flush() error {\n\tcc.mu.Lock()\n\tpendingBySpanID := cc.pendingBySpanID\n\tpending := cc.pending\n\tcc.pendingBySpanID = nil\n\tcc.pending = nil\n\tcc.mu.Unlock()\n\n\tvar errs []error\n\tfor _, spanID := range pending {\n\t\tp := pendingBySpanID[spanID]\n\t\tif err := cc.Collector.Collect(spanIDFromWire(p.Spanid), annotationsFromWire(p.Annotation)...); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tif len(errs) == 1 {\n\t\treturn errs[0]\n\t} else if len(errs) > 1 {\n\t\treturn fmt.Errorf(\"ChunkedCollector: multiple errors: %v\", errs)\n\t}\n\treturn nil\n}", "func (collector *Collector) Collect(ch chan<- prometheus.Metric) {\n\tch <- prometheus.MustNewConstMetric(collector.incidentsCreatedCount, prometheus.CounterValue, collector.storage.GetIncidentsCreatedCount())\n}", "func (d *decorator) Collect(in chan<- prometheus.Metric) {\n\td.duration.Collect(in)\n\td.requests.Collect(in)\n}", "func Collect(metrics []Metric, c CloudWatchService, namespace string) {\n\tid, err := GetInstanceID()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor _, metric := range metrics {\n\t\tmetric.Collect(id, c, namespace)\n\t}\n}", "func (c *beatCollector) Collect(ch chan<- prometheus.Metric) {\n\n\tfor _, i := range c.metrics {\n\t\tch <- prometheus.MustNewConstMetric(i.desc, i.valType, i.eval(c.stats))\n\t}\n\n}", "func (b *EBPFTelemetry) Collect(ch chan<- prometheus.Metric) {\n\tb.getHelpersTelemetry(ch)\n\tb.getMapsTelemetry(ch)\n}", "func (c *metricbeatCollector) Collect(ch chan<- prometheus.Metric) {\n\n\tfor _, i := range c.metrics {\n\t\tch <- prometheus.MustNewConstMetric(i.desc, i.valType, i.eval(c.stats))\n\t}\n\n}", "func (c *Collector) Collect(ch chan<- prometheus.Metric) {\n\tc.mut.RLock()\n\tdefer c.mut.RUnlock()\n\n\tif c.inner != nil {\n\t\tc.inner.Collect(ch)\n\t}\n}", "func (c *filebeatCollector) Collect(ch chan<- prometheus.Metric) {\n\n\tfor _, i := range c.metrics {\n\t\tch <- prometheus.MustNewConstMetric(i.desc, i.valType, i.eval(c.stats))\n\t}\n\n}", "func (c *Exporter) Collect(ch chan<- prometheus.Metric) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\tfor _, cc := range c.collectors {\n\t\tcc.Collect(ch)\n\t}\n}", "func (c *Exporter) Collect(ch chan<- prometheus.Metric) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\tfor _, cc := range c.collectors {\n\t\tcc.Collect(ch)\n\t}\n}", "func (mlw *Wrapper) Collect() {\n\tmlw.ml.Collect()\n\tsort.Sort(byLatency(mlw.ml.Results))\n}", "func (collector *MetricsCollector) Collect(ch chan<- prometheus.Metric) {\n\tfilterMetricsByKind := func(kind string, orgMetrics []constMetric) (filteredMetrics []constMetric) {\n\t\tfor _, metric := range orgMetrics {\n\t\t\tif metric.kind == kind {\n\t\t\t\tfilteredMetrics = append(filteredMetrics, metric)\n\t\t\t}\n\t\t}\n\t\treturn filteredMetrics\n\t}\n\tcollector.defMetrics.reset()\n\tfor k := range collector.metrics {\n\t\tcounters := filterMetricsByKind(config.KeyMetricTypeCounter, collector.metrics[k])\n\t\tgauges := filterMetricsByKind(config.KeyMetricTypeGauge, collector.metrics[k])\n\t\thistograms := filterMetricsByKind(config.KeyMetricTypeHistogram, collector.metrics[k])\n\t\tcollectCounters(counters, collector.defMetrics, ch)\n\t\tcollectGauges(gauges, collector.defMetrics, ch)\n\t\tcollectHistograms(histograms, collector.defMetrics, ch)\n\t\tcollector.cache.Reset()\n\t}\n\tcollector.defMetrics.collectDefaultMetrics(ch)\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mu.Lock()\n\tdefer e.mu.Unlock()\n\n\tfor _, cc := range e.collectors {\n\t\tcc.Collect(ch)\n\t}\n}", "func (c *collector) Collect(ch chan<- prometheus.Metric) {\n\tc.m.Lock()\n\tfor _, m := range c.metrics {\n\t\tch <- m.metric\n\t}\n\tc.m.Unlock()\n}", "func (c *Aggregator) Collect(ctx context.Context, rec export.Record, exp export.Batcher) {\n\tc.checkpoint = c.current.SwapNumberAtomic(core.Number(0))\n\n\texp.Export(ctx, rec, c)\n}", "func (a *MetricAggregator) Flush(flushInterval time.Duration) {\n\ta.statser.Gauge(\"aggregator.metricmaps_received\", float64(a.metricMapsReceived), nil)\n\n\tflushInSeconds := float64(flushInterval) / float64(time.Second)\n\n\ta.metricMap.Counters.Each(func(key, tagsKey string, counter gostatsd.Counter) {\n\t\tcounter.PerSecond = float64(counter.Value) / flushInSeconds\n\t\ta.metricMap.Counters[key][tagsKey] = counter\n\t})\n\n\ta.metricMap.Timers.Each(func(key, tagsKey string, timer gostatsd.Timer) {\n\t\tif hasHistogramTag(timer) {\n\t\t\ttimer.Histogram = latencyHistogram(timer, a.histogramLimit)\n\t\t\ta.metricMap.Timers[key][tagsKey] = timer\n\t\t\treturn\n\t\t}\n\n\t\tif count := len(timer.Values); count > 0 {\n\t\t\tsort.Float64s(timer.Values)\n\t\t\ttimer.Min = timer.Values[0]\n\t\t\ttimer.Max = timer.Values[count-1]\n\t\t\tn := len(timer.Values)\n\t\t\tcount := float64(n)\n\n\t\t\tcumulativeValues := make([]float64, n)\n\t\t\tcumulSumSquaresValues := make([]float64, n)\n\t\t\tcumulativeValues[0] = timer.Min\n\t\t\tcumulSumSquaresValues[0] = timer.Min * timer.Min\n\t\t\tfor i := 1; i < n; i++ {\n\t\t\t\tcumulativeValues[i] = timer.Values[i] + cumulativeValues[i-1]\n\t\t\t\tcumulSumSquaresValues[i] = timer.Values[i]*timer.Values[i] + cumulSumSquaresValues[i-1]\n\t\t\t}\n\n\t\t\tvar sumSquares = timer.Min * timer.Min\n\t\t\tvar mean = timer.Min\n\t\t\tvar sum = timer.Min\n\t\t\tvar thresholdBoundary = timer.Max\n\n\t\t\tfor pct, pctStruct := range a.percentThresholds {\n\t\t\t\tnumInThreshold := n\n\t\t\t\tif n > 1 {\n\t\t\t\t\tnumInThreshold = int(round(math.Abs(pct) / 100 * count))\n\t\t\t\t\tif numInThreshold == 0 {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif pct > 0 {\n\t\t\t\t\t\tthresholdBoundary = timer.Values[numInThreshold-1]\n\t\t\t\t\t\tsum = cumulativeValues[numInThreshold-1]\n\t\t\t\t\t\tsumSquares = cumulSumSquaresValues[numInThreshold-1]\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthresholdBoundary = timer.Values[n-numInThreshold]\n\t\t\t\t\t\tsum = cumulativeValues[n-1] - cumulativeValues[n-numInThreshold-1]\n\t\t\t\t\t\tsumSquares = cumulSumSquaresValues[n-1] - cumulSumSquaresValues[n-numInThreshold-1]\n\t\t\t\t\t}\n\t\t\t\t\tmean = sum / float64(numInThreshold)\n\t\t\t\t}\n\n\t\t\t\tif !a.disabledSubtypes.CountPct {\n\t\t\t\t\ttimer.Percentiles.Set(pctStruct.count, float64(numInThreshold))\n\t\t\t\t}\n\t\t\t\tif !a.disabledSubtypes.MeanPct {\n\t\t\t\t\ttimer.Percentiles.Set(pctStruct.mean, mean)\n\t\t\t\t}\n\t\t\t\tif !a.disabledSubtypes.SumPct {\n\t\t\t\t\ttimer.Percentiles.Set(pctStruct.sum, sum)\n\t\t\t\t}\n\t\t\t\tif !a.disabledSubtypes.SumSquaresPct {\n\t\t\t\t\ttimer.Percentiles.Set(pctStruct.sumSquares, sumSquares)\n\t\t\t\t}\n\t\t\t\tif pct > 0 {\n\t\t\t\t\tif !a.disabledSubtypes.UpperPct {\n\t\t\t\t\t\ttimer.Percentiles.Set(pctStruct.upper, thresholdBoundary)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif !a.disabledSubtypes.LowerPct {\n\t\t\t\t\t\ttimer.Percentiles.Set(pctStruct.lower, thresholdBoundary)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tsum = cumulativeValues[n-1]\n\t\t\tsumSquares = cumulSumSquaresValues[n-1]\n\t\t\tmean = sum / count\n\n\t\t\tvar sumOfDiffs float64\n\t\t\tfor i := 0; i < n; i++ {\n\t\t\t\tsumOfDiffs += (timer.Values[i] - mean) * (timer.Values[i] - mean)\n\t\t\t}\n\n\t\t\tmid := int(math.Floor(count / 2))\n\t\t\tif math.Mod(count, 2) == 0 {\n\t\t\t\ttimer.Median = (timer.Values[mid-1] + timer.Values[mid]) / 2\n\t\t\t} else {\n\t\t\t\ttimer.Median = timer.Values[mid]\n\t\t\t}\n\n\t\t\ttimer.Mean = mean\n\t\t\ttimer.StdDev = math.Sqrt(sumOfDiffs / count)\n\t\t\ttimer.Sum = sum\n\t\t\ttimer.SumSquares = sumSquares\n\n\t\t\ttimer.Count = int(round(timer.SampledCount))\n\t\t\ttimer.PerSecond = timer.SampledCount / flushInSeconds\n\t\t} else {\n\t\t\ttimer.Count = 0\n\t\t\ttimer.SampledCount = 0\n\t\t\ttimer.PerSecond = 0\n\t\t}\n\t\ta.metricMap.Timers[key][tagsKey] = timer\n\t})\n}", "func (c *Collector) Collect(scs []stats.SampleContainer) {\n\tc.lock.Lock()\n\tfor _, sc := range scs {\n\t\tc.Samples = append(c.Samples, sc.GetSamples()...)\n\t}\n\tc.lock.Unlock()\n}", "func (c *auditdCollector) Collect(ch chan<- prometheus.Metric) {\n\n\tfor _, i := range c.metrics {\n\t\tch <- prometheus.MustNewConstMetric(i.desc, i.valType, i.eval(c.stats))\n\t}\n\n}", "func (e *ServiceQuotasExporter) Collect(ch chan<- prometheus.Metric) {\n\tquotas, err := e.quotasClient.QuotasAndUsage()\n\tif err != nil {\n\t\tlog.Errorf(\"Can not retrieve quotas and limits: %s\", err)\n\t}\n\n\tfor _, quota := range quotas {\n\t\tresourceID := quota.Identifier()\n\n\t\tmetricLimit, ok := e.metricsQuotaLimit[resourceID]\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tch <- prometheus.MustNewConstMetric(metricLimit, prometheus.GaugeValue, quota.Quota, resourceID)\n\n\t\tmetricUsed, ok := e.metricsUsedQuota[resourceID]\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tch <- prometheus.MustNewConstMetric(metricUsed, prometheus.GaugeValue, quota.Usage, resourceID)\n\t}\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.withCollectors(func(cs []prometheus.Collector) {\n\t\tfor _, c := range cs {\n\t\t\tc.Collect(ch)\n\t\t}\n\t})\n}", "func (o *requestMetrics) Collect(ch chan<- prometheus.Metric) {\n\tmetricFamilies, err := o.stStore.GetPromDirectMetrics()\n\tif err != nil {\n\t\tklog.Errorf(\"fetch prometheus metrics failed: %v\", err)\n\t\treturn\n\t}\n\to.handleMetrics(metricFamilies, ch)\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n\tif err := e.collect(ch); err != nil {\n\t\tlog.Errorf(\"Error scraping ingestor: %s\", err)\n\t}\n\treturn\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n\n\tif err := e.scrape(); err != nil {\n\t\tlog.Error(err)\n\t\tnomad_up.Set(0)\n\t\tch <- nomad_up\n\t\treturn\n\t}\n\n\tch <- nomad_up\n\tch <- metric_uptime\n\tch <- metric_request_response_time_total\n\tch <- metric_request_response_time_avg\n\n\tfor _, metric := range metric_request_status_count_current {\n\t\tch <- metric\n\t}\n\tfor _, metric := range metric_request_status_count_total {\n\t\tch <- metric\n\t}\n}", "func (c *VMCollector) Collect(ch chan<- prometheus.Metric) {\n\tfor _, m := range c.getMetrics() {\n\t\tch <- m\n\t}\n}", "func (collector *Metrics) Collect(ch chan<- prometheus.Metric) {\n\n\tcollectedIssues, err := fetchJiraIssues()\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn\n\t}\n\n\tfor _, issue := range collectedIssues.Issues {\n\t\tcreatedTimestamp := convertToUnixTime(issue.Fields.Created)\n\t\tch <- prometheus.MustNewConstMetric(collector.issue, prometheus.CounterValue, createdTimestamp, issue.Fields.Status.Name, issue.Fields.Project.Name, issue.Key, issue.Fields.Assignee.Name, issue.Fields.Location.Name, issue.Fields.Priority.Name, issue.Fields.Level.Name, issue.Fields.RequestType.Name, issue.Fields.Feedback, issue.Fields.Urgency.Name, issue.Fields.IssueType.Name, issue.Fields.Reporter.Name, issue.Fields.Satisfaction)\n\t}\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n\n\t// Reset metrics.\n\tfor _, vec := range e.gauges {\n\t\tvec.Reset()\n\t}\n\n\tfor _, vec := range e.counters {\n\t\tvec.Reset()\n\t}\n\n\tresp, err := e.client.Get(e.URI)\n\tif err != nil {\n\t\te.up.Set(0)\n\t\tlog.Printf(\"Error while querying Elasticsearch: %v\", err)\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\n\tif err != nil {\n\t\tlog.Printf(\"Failed to read ES response body: %v\", err)\n\t\te.up.Set(0)\n\t\treturn\n\t}\n\n\te.up.Set(1)\n\n\tvar all_stats NodeStatsResponse\n\terr = json.Unmarshal(body, &all_stats)\n\n\tif err != nil {\n\t\tlog.Printf(\"Failed to unmarshal JSON into struct: %v\", err)\n\t\treturn\n\t}\n\n\t// Regardless of whether we're querying the local host or the whole\n\t// cluster, here we can just iterate through all nodes found.\n\n\tfor node, stats := range all_stats.Nodes {\n\t\tlog.Printf(\"Processing node %v\", node)\n\t\t// GC Stats\n\t\tfor collector, gcstats := range stats.JVM.GC.Collectors {\n\t\t\te.counters[\"jvm_gc_collection_count\"].WithLabelValues(all_stats.ClusterName, stats.Name, collector).Set(float64(gcstats.CollectionCount))\n\t\t\te.counters[\"jvm_gc_collection_time_in_millis\"].WithLabelValues(all_stats.ClusterName, stats.Name, collector).Set(float64(gcstats.CollectionTime))\n\t\t}\n\n\t\t// Breaker stats\n\t\tfor breaker, bstats := range stats.Breakers {\n\t\t\te.gauges[\"breakers_estimated_size_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name, breaker).Set(float64(bstats.EstimatedSize))\n\t\t\te.gauges[\"breakers_limit_size_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name, breaker).Set(float64(bstats.LimitSize))\n\t\t}\n\n\t\t// JVM Memory Stats\n\t\te.gauges[\"jvm_mem_heap_committed_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.JVM.Mem.HeapCommitted))\n\t\te.gauges[\"jvm_mem_heap_used_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.JVM.Mem.HeapUsed))\n\t\te.gauges[\"jvm_mem_heap_max_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.JVM.Mem.HeapMax))\n\t\te.gauges[\"jvm_mem_non_heap_committed_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.JVM.Mem.NonHeapCommitted))\n\t\te.gauges[\"jvm_mem_non_heap_used_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.JVM.Mem.NonHeapUsed))\n\n\t\t// Indices Stats\n\t\te.gauges[\"indices_fielddata_evictions\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.FieldData.Evictions))\n\t\te.gauges[\"indices_fielddata_memory_size_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.FieldData.MemorySize))\n\t\te.gauges[\"indices_filter_cache_evictions\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.FilterCache.Evictions))\n\t\te.gauges[\"indices_filter_cache_memory_size_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.FilterCache.MemorySize))\n\n\t\te.gauges[\"indices_docs_count\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.Docs.Count))\n\t\te.gauges[\"indices_docs_deleted\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.Docs.Deleted))\n\n\t\te.gauges[\"indices_segments_memory_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.Segments.Memory))\n\n\t\te.gauges[\"indices_store_size_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.Store.Size))\n\t\te.counters[\"indices_store_throttle_time_in_millis\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.Store.ThrottleTime))\n\n\t\te.counters[\"indices_flush_total\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.Flush.Total))\n\t\te.counters[\"indices_flush_time_in_millis\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.Flush.Time))\n\n\t\t// Transport Stats\n\t\te.counters[\"transport_rx_count\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Transport.RxCount))\n\t\te.counters[\"transport_rx_size_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Transport.RxSize))\n\t\te.counters[\"transport_tx_count\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Transport.TxCount))\n\t\te.counters[\"transport_tx_size_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Transport.TxSize))\n\t}\n\n\t// Report metrics.\n\tch <- e.up\n\n\tfor _, vec := range e.counters {\n\t\tvec.Collect(ch)\n\t}\n\n\tfor _, vec := range e.gauges {\n\t\tvec.Collect(ch)\n\t}\n}", "func (c *libbeatCollector) Collect(ch chan<- prometheus.Metric) {\n\n\tfor _, i := range c.metrics {\n\t\tch <- prometheus.MustNewConstMetric(i.desc, i.valType, i.eval(c.stats))\n\t}\n\n\t// output.type with dynamic label\n\tch <- prometheus.MustNewConstMetric(libbeatOutputType, prometheus.CounterValue, float64(1), c.stats.LibBeat.Output.Type)\n\n}", "func (t *TimestampCollector) Collect(ch chan<- prometheus.Metric) {\n\t// New map to dedup filenames.\n\tuniqueFiles := make(map[string]float64)\n\tt.lock.RLock()\n\tfor fileSD := range t.discoverers {\n\t\tfileSD.lock.RLock()\n\t\tfor filename, timestamp := range fileSD.timestamps {\n\t\t\tuniqueFiles[filename] = timestamp\n\t\t}\n\t\tfileSD.lock.RUnlock()\n\t}\n\tt.lock.RUnlock()\n\tfor filename, timestamp := range uniqueFiles {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tt.Description,\n\t\t\tprometheus.GaugeValue,\n\t\t\ttimestamp,\n\t\t\tfilename,\n\t\t)\n\t}\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n\tif err := e.collect(ch); err != nil {\n\t\tlog.Errorf(\"Error scraping: %s\", err)\n\t}\n\treturn\n}", "func (e *exporter) Collect(ch chan<- prometheus.Metric) {\n\twg := sync.WaitGroup{}\n\twg.Add(len(e.Collectors))\n\tfor name, c := range e.Collectors {\n\t\tgo func(name string, c Collector) {\n\t\t\texecute(name, c, ch)\n\t\t\twg.Done()\n\t\t}(name, c)\n\t}\n\twg.Wait()\n}", "func (c *Collector) Collect(sampleContainers []stats.SampleContainer) {\n\tselect {\n\tcase <-c.stopSendingMetricsCh:\n\t\treturn\n\tdefault:\n\t}\n\n\tif c.referenceID == \"\" {\n\t\treturn\n\t}\n\n\tnewSamples := []*Sample{}\n\tnewHTTPTrails := []*httpext.Trail{}\n\n\tfor _, sampleContainer := range sampleContainers {\n\t\tswitch sc := sampleContainer.(type) {\n\t\tcase *httpext.Trail:\n\t\t\tsc = useCloudTags(sc)\n\t\t\t// Check if aggregation is enabled,\n\t\t\tif c.config.AggregationPeriod.Duration > 0 {\n\t\t\t\tnewHTTPTrails = append(newHTTPTrails, sc)\n\t\t\t} else {\n\t\t\t\tnewSamples = append(newSamples, NewSampleFromTrail(sc))\n\t\t\t}\n\t\tcase *netext.NetTrail:\n\t\t\t// TODO: aggregate?\n\t\t\tvalues := map[string]float64{\n\t\t\t\tmetrics.DataSent.Name: float64(sc.BytesWritten),\n\t\t\t\tmetrics.DataReceived.Name: float64(sc.BytesRead),\n\t\t\t}\n\n\t\t\tif sc.FullIteration {\n\t\t\t\tvalues[metrics.IterationDuration.Name] = stats.D(sc.EndTime.Sub(sc.StartTime))\n\t\t\t\tvalues[metrics.Iterations.Name] = 1\n\t\t\t}\n\n\t\t\tnewSamples = append(newSamples, &Sample{\n\t\t\t\tType: DataTypeMap,\n\t\t\t\tMetric: \"iter_li_all\",\n\t\t\t\tData: &SampleDataMap{\n\t\t\t\t\tTime: toMicroSecond(sc.GetTime()),\n\t\t\t\t\tTags: sc.GetTags(),\n\t\t\t\t\tValues: values,\n\t\t\t\t},\n\t\t\t})\n\t\tdefault:\n\t\t\tfor _, sample := range sampleContainer.GetSamples() {\n\t\t\t\tnewSamples = append(newSamples, &Sample{\n\t\t\t\t\tType: DataTypeSingle,\n\t\t\t\t\tMetric: sample.Metric.Name,\n\t\t\t\t\tData: &SampleDataSingle{\n\t\t\t\t\t\tType: sample.Metric.Type,\n\t\t\t\t\t\tTime: toMicroSecond(sample.Time),\n\t\t\t\t\t\tTags: sample.Tags,\n\t\t\t\t\t\tValue: sample.Value,\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(newSamples) > 0 || len(newHTTPTrails) > 0 {\n\t\tc.bufferMutex.Lock()\n\t\tc.bufferSamples = append(c.bufferSamples, newSamples...)\n\t\tc.bufferHTTPTrails = append(c.bufferHTTPTrails, newHTTPTrails...)\n\t\tc.bufferMutex.Unlock()\n\t}\n}", "func (p *Collector) Collect(c chan<- prometheus.Metric) {\n\tp.Sink.mu.Lock()\n\tdefer p.Sink.mu.Unlock()\n\n\texpire := p.Sink.expiration != 0\n\tnow := time.Now()\n\tfor k, v := range p.Sink.gauges {\n\t\tlast := p.Sink.updates[k]\n\t\tif expire && last.Add(p.Sink.expiration).Before(now) {\n\t\t\tdelete(p.Sink.updates, k)\n\t\t\tdelete(p.Sink.gauges, k)\n\t\t} else {\n\t\t\tv.Collect(c)\n\t\t}\n\t}\n\tfor k, v := range p.Sink.summaries {\n\t\tlast := p.Sink.updates[k]\n\t\tif expire && last.Add(p.Sink.expiration).Before(now) {\n\t\t\tdelete(p.Sink.updates, k)\n\t\t\tdelete(p.Sink.summaries, k)\n\t\t} else {\n\t\t\tv.Collect(c)\n\t\t}\n\t}\n\tfor k, v := range p.Sink.counters {\n\t\tlast := p.Sink.updates[k]\n\t\tif expire && last.Add(p.Sink.expiration).Before(now) {\n\t\t\tdelete(p.Sink.updates, k)\n\t\t\tdelete(p.Sink.counters, k)\n\t\t} else {\n\t\t\tv.Collect(c)\n\t\t}\n\t}\n}", "func (c *collector) Collect(ch chan<- prometheus.Metric) {\n\tc.mu.Lock()\n\t// Get the last views\n\tviews := c.views\n\t// Now clear them out for the next accumulation\n\tc.views = c.views[:0]\n\tc.mu.Unlock()\n\n\tif len(views) == 0 {\n\t\treturn\n\t}\n\n\t// seen is necessary because within each Collect cycle\n\t// if a Metric is sent to Prometheus with the same make up\n\t// that is \"name\" and \"labels\", it will error out.\n\tseen := make(map[prometheus.Metric]bool)\n\n\tfor _, vd := range views {\n\t\tfor _, row := range vd.Rows {\n\t\t\tmetric := c.toMetric(vd.View, row)\n\t\t\tif _, ok := seen[metric]; !ok && metric != nil {\n\t\t\t\tch <- metric\n\t\t\t\tseen[metric] = true\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *analysisRunCollector) Collect(ch chan<- prometheus.Metric) {\n\tanalysisRuns, err := c.store.List(labels.NewSelector())\n\tif err != nil {\n\t\tlog.Warnf(\"Failed to collect analysisRuns: %v\", err)\n\t\treturn\n\t}\n\tfor _, ar := range analysisRuns {\n\t\tcollectAnalysisRuns(ch, ar)\n\t}\n}", "func (h *Metrics) Collect(in chan<- prometheus.Metric) {\n\th.duration.Collect(in)\n\th.totalRequests.Collect(in)\n\th.requestSize.Collect(in)\n\th.responseSize.Collect(in)\n\th.handlerStatuses.Collect(in)\n\th.responseTime.Collect(in)\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n\tif err := e.scrape(ch); err != nil {\n\t\tlog.Printf(\"Error scraping nightscout url: %s\", err)\n\t}\n\n\te.statusNightscout.Collect(ch)\n\n\treturn\n}", "func (r *RGWCollector) Collect(ch chan<- prometheus.Metric, version *Version) {\n\tif !r.background {\n\t\tr.logger.WithField(\"background\", r.background).Debug(\"collecting RGW GC stats\")\n\t\terr := r.collect()\n\t\tif err != nil {\n\t\t\tr.logger.WithField(\"background\", r.background).WithError(err).Error(\"error collecting RGW GC stats\")\n\t\t}\n\t}\n\n\tfor _, metric := range r.collectorList() {\n\t\tmetric.Collect(ch)\n\t}\n}", "func (e *ebpfConntracker) Collect(ch chan<- prometheus.Metric) {\n\tebpfTelemetry := &netebpf.ConntrackTelemetry{}\n\tif err := e.telemetryMap.Lookup(unsafe.Pointer(&zero), unsafe.Pointer(ebpfTelemetry)); err != nil {\n\t\tlog.Tracef(\"error retrieving the telemetry struct: %s\", err)\n\t} else {\n\t\tdelta := ebpfTelemetry.Registers - conntrackerTelemetry.lastRegisters\n\t\tconntrackerTelemetry.lastRegisters = ebpfTelemetry.Registers\n\t\tch <- prometheus.MustNewConstMetric(conntrackerTelemetry.registersTotal, prometheus.CounterValue, float64(delta))\n\t}\n}", "func (a collectorAdapter) Collect(ch chan<- prometheus.Metric) {\n\tif err := a.Update(ch); err != nil {\n\t\tpanic(fmt.Sprintf(\"failed to update collector: %v\", err))\n\t}\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n\tif err := e.collect(ch); err != nil {\n\t\tglog.Error(fmt.Sprintf(\"Error collecting stats: %s\", err))\n\t}\n\treturn\n}", "func (r *RegionStatistics) Collect() {\n\tr.RLock()\n\tdefer r.RUnlock()\n\tregionMissPeerRegionCounter.Set(float64(len(r.stats[MissPeer])))\n\tregionExtraPeerRegionCounter.Set(float64(len(r.stats[ExtraPeer])))\n\tregionDownPeerRegionCounter.Set(float64(len(r.stats[DownPeer])))\n\tregionPendingPeerRegionCounter.Set(float64(len(r.stats[PendingPeer])))\n\tregionOfflinePeerRegionCounter.Set(float64(len(r.stats[OfflinePeer])))\n\tregionLearnerPeerRegionCounter.Set(float64(len(r.stats[LearnerPeer])))\n\tregionEmptyRegionCounter.Set(float64(len(r.stats[EmptyRegion])))\n\tregionOversizedRegionCounter.Set(float64(len(r.stats[OversizedRegion])))\n\tregionUndersizedRegionCounter.Set(float64(len(r.stats[UndersizedRegion])))\n\tregionWitnessLeaderRegionCounter.Set(float64(len(r.stats[WitnessLeader])))\n}", "func (c *CephExporter) Collect(ch chan<- prometheus.Metric) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\tfor _, cc := range c.collectors {\n\t\tcc.Collect(ch)\n\t}\n}", "func (m *Metrics) Collect() error {\n\tfor range time.Tick(m.cInterval) {\n\t\tcontainers, err := m.docker.ContainerList()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfor _, container := range containers {\n\t\t\tif _, ok := m.metrics[container.Names[0][1:]]; !ok {\n\t\t\t\tgo func() {\n\t\t\t\t\tif err := m.collect(container.Names[0][1:]); err != nil {\n\t\t\t\t\t\tlog.Fatal().Err(err).Msg(\"collection metrics error\")\n\t\t\t\t\t}\n\t\t\t\t}()\n\t\t\t\tlog.Info().Msgf(\"new container %s\", container.Names[0][1:])\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\tjunosTotalScrapeCount++\n\tch <- prometheus.MustNewConstMetric(junosDesc[\"ScrapesTotal\"], prometheus.CounterValue, junosTotalScrapeCount)\n\n\twg := &sync.WaitGroup{}\n\tfor _, collector := range e.Collectors {\n\t\twg.Add(1)\n\t\tgo e.runCollector(ch, collector, wg)\n\t}\n\twg.Wait()\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n\n\tup := e.scrape(ch)\n\n\tch <- prometheus.MustNewConstMetric(artifactoryUp, prometheus.GaugeValue, up)\n\tch <- e.totalScrapes\n\tch <- e.jsonParseFailures\n}", "func (m *ClientMetrics) Collect(ch chan<- prom.Metric) {\n\tm.clientStartedCounter.Collect(ch)\n\tm.clientHandledCounter.Collect(ch)\n\tm.clientStreamMsgReceived.Collect(ch)\n\tm.clientStreamMsgSent.Collect(ch)\n\tif m.clientHandledHistogramEnabled {\n\t\tm.clientHandledHistogram.Collect(ch)\n\t}\n}", "func (c *Client) Collect(s stat.Stat) error {\n\tbuf, err := json.Marshal(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq, err := http.NewRequest(\"POST\", fmt.Sprintf(\"%s/collect\", c.url), bytes.NewBuffer(buf))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 200 {\n\t\treturn errors.Wrap(errors.New(resp.Status), \"statscoll\")\n\t}\n\n\treturn nil\n}", "func (c *goCollector) Collect(ch chan<- Metric) {\n\t// Collect base non-memory metrics.\n\tc.base.Collect(ch)\n\n\tif len(c.sampleBuf) == 0 {\n\t\treturn\n\t}\n\n\t// Collect must be thread-safe, so prevent concurrent use of\n\t// sampleBuf elements. Just read into sampleBuf but write all the data\n\t// we get into our Metrics or MemStats.\n\t//\n\t// This lock also ensures that the Metrics we send out are all from\n\t// the same updates, ensuring their mutual consistency insofar as\n\t// is guaranteed by the runtime/metrics package.\n\t//\n\t// N.B. This locking is heavy-handed, but Collect is expected to be called\n\t// relatively infrequently. Also the core operation here, metrics.Read,\n\t// is fast (O(tens of microseconds)) so contention should certainly be\n\t// low, though channel operations and any allocations may add to that.\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\t// Populate runtime/metrics sample buffer.\n\tmetrics.Read(c.sampleBuf)\n\n\t// Collect all our runtime/metrics user chose to expose from sampleBuf (if any).\n\tfor i, metric := range c.rmExposedMetrics {\n\t\t// We created samples for exposed metrics first in order, so indexes match.\n\t\tsample := c.sampleBuf[i]\n\n\t\t// N.B. switch on concrete type because it's significantly more efficient\n\t\t// than checking for the Counter and Gauge interface implementations. In\n\t\t// this case, we control all the types here.\n\t\tswitch m := metric.(type) {\n\t\tcase *counter:\n\t\t\t// Guard against decreases. This should never happen, but a failure\n\t\t\t// to do so will result in a panic, which is a harsh consequence for\n\t\t\t// a metrics collection bug.\n\t\t\tv0, v1 := m.get(), unwrapScalarRMValue(sample.Value)\n\t\t\tif v1 > v0 {\n\t\t\t\tm.Add(unwrapScalarRMValue(sample.Value) - m.get())\n\t\t\t}\n\t\t\tm.Collect(ch)\n\t\tcase *gauge:\n\t\t\tm.Set(unwrapScalarRMValue(sample.Value))\n\t\t\tm.Collect(ch)\n\t\tcase *batchHistogram:\n\t\t\tm.update(sample.Value.Float64Histogram(), c.exactSumFor(sample.Name))\n\t\t\tm.Collect(ch)\n\t\tdefault:\n\t\t\tpanic(\"unexpected metric type\")\n\t\t}\n\t}\n\n\tif c.msMetricsEnabled {\n\t\t// ms is a dummy MemStats that we populate ourselves so that we can\n\t\t// populate the old metrics from it if goMemStatsCollection is enabled.\n\t\tvar ms runtime.MemStats\n\t\tmemStatsFromRM(&ms, c.sampleMap)\n\t\tfor _, i := range c.msMetrics {\n\t\t\tch <- MustNewConstMetric(i.desc, i.valType, i.eval(&ms))\n\t\t}\n\t}\n}", "func (c *interfaceCollector) Collect(client *rpc.Client, ch chan<- prometheus.Metric, labelValues []string) error {\n\tstats, err := c.interfaceStats(client)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, s := range stats {\n\t\tc.collectForInterface(s, ch, labelValues)\n\t}\n\n\treturn nil\n}", "func (c *logMetricsCollector) CollectWithStability(ch chan<- metrics.Metric) {\n\tpodStats, err := c.podStats(context.Background())\n\tif err != nil {\n\t\tklog.ErrorS(err, \"Failed to get pod stats\")\n\t\treturn\n\t}\n\n\tfor _, ps := range podStats {\n\t\tfor _, c := range ps.Containers {\n\t\t\tif c.Logs != nil && c.Logs.UsedBytes != nil {\n\t\t\t\tch <- metrics.NewLazyConstMetric(\n\t\t\t\t\tdescLogSize,\n\t\t\t\t\tmetrics.GaugeValue,\n\t\t\t\t\tfloat64(*c.Logs.UsedBytes),\n\t\t\t\t\tps.PodRef.UID,\n\t\t\t\t\tps.PodRef.Namespace,\n\t\t\t\t\tps.PodRef.Name,\n\t\t\t\t\tc.Name,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n}", "func (p *promProducer) Collect(ch chan<- prometheus.Metric) {\n\tfor _, obj := range p.store.Objects() {\n\t\tmessage, ok := obj.(producers.MetricsMessage)\n\t\tif !ok {\n\t\t\tpromLog.Warnf(\"Unsupported message type %T\", obj)\n\t\t\tcontinue\n\t\t}\n\t\tdims := dimsToMap(message.Dimensions)\n\n\t\tfor _, d := range message.Datapoints {\n\t\t\tpromLog.Debugf(\"Processing datapoint %s\", d.Name)\n\t\t\tvar tagKeys []string\n\t\t\tvar tagVals []string\n\t\t\tfor k, v := range dims {\n\t\t\t\ttagKeys = append(tagKeys, sanitizeName(k))\n\t\t\t\ttagVals = append(tagVals, v)\n\t\t\t}\n\t\t\tfor k, v := range d.Tags {\n\t\t\t\ttagKeys = append(tagKeys, sanitizeName(k))\n\t\t\t\ttagVals = append(tagVals, v)\n\t\t\t}\n\n\t\t\tname := sanitizeName(d.Name)\n\t\t\tval, err := coerceToFloat(d.Value)\n\t\t\tif err != nil {\n\t\t\t\tpromLog.Warnf(\"Bad datapoint value %q: %s\", d.Value, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tdesc := prometheus.NewDesc(name, \"DC/OS Metrics Datapoint\", tagKeys, nil)\n\t\t\tmetric, err := prometheus.NewConstMetric(desc, prometheus.GaugeValue, val, tagVals...)\n\t\t\tif err != nil {\n\t\t\t\tpromLog.Warnf(\"Could not create Prometheus metric %s: %s\", name, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tpromLog.Debugf(\"Emitting datapoint %s\", name)\n\t\t\tch <- metric\n\t\t}\n\n\t}\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\t// Protect metrics from concurrent collects.\n\te.mutex.Lock()\n\tdefer e.mutex.Unlock()\n\n\t// Scrape metrics from Tankerkoenig API.\n\tif err := e.scrape(ch); err != nil {\n\t\te.logger.Printf(\"error: cannot scrape tankerkoenig api: %v\", err)\n\t}\n\n\t// Collect metrics.\n\te.up.Collect(ch)\n\te.scrapeDuration.Collect(ch)\n\te.failedScrapes.Collect(ch)\n\te.totalScrapes.Collect(ch)\n}", "func (p *statelessAsyncInstrument[N, Storage, Methods]) Collect(seq data.Sequence, output *[]data.Instrument) {\n\tp.instLock.Lock()\n\tdefer p.instLock.Unlock()\n\n\tioutput := p.appendInstrument(output)\n\n\tfor set, entry := range p.data {\n\t\tp.appendPoint(ioutput, set, &entry.storage, aggregation.CumulativeTemporality, seq.Start, seq.Now, false)\n\t}\n\n\t// Reset the entire map.\n\tp.data = map[attribute.Set]*storageHolder[Storage, notUsed]{}\n}", "func (c *bgpCollector) Collect(client collector.Client, ch chan<- prometheus.Metric, labelValues []string) error {\n\terr := c.collect(client, ch, labelValues)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (fl *flusher) Flush(ctx context.Context, span opentracing.Span, classrooms []models.Classroom) []models.Classroom {\n\n\tchunks, err := utils.SplitSlice(classrooms, fl.chunkSize)\n\n\tif err != nil {\n\t\treturn classrooms\n\t}\n\n\tfor i, chunk := range chunks {\n\n\t\tvar childSpan opentracing.Span\n\t\tif span != nil {\n\t\t\tchildSpan = opentracing.StartSpan(\"Flush\", opentracing.ChildOf(span.Context()))\n\t\t}\n\n\t\t_, err := fl.repo.MultiAddClassroom(ctx, chunk)\n\n\t\tif span != nil {\n\n\t\t\tchildSpan.LogFields(\n\t\t\t\tlog.Int(\"len\", len(chunk)),\n\t\t\t\tlog.Bool(\"sent\", err == nil),\n\t\t\t)\n\t\t\tchildSpan.Finish()\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn classrooms[fl.chunkSize*i:]\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m httpPostMetrics) Collect(metrics chan<- prometheus.Metric) {\n\tm.totalTime.Collect(metrics)\n\tm.firstProgressPacket.Collect(metrics)\n\tm.firstPackPacket.Collect(metrics)\n\tm.packBytes.Collect(metrics)\n}", "func (m *ClientMetrics) Collect(ch chan<- prometheus.Metric) {\n\tm.clientHandledSummary.Collect(ch)\n}", "func (m *MeterImpl) CollectAsync(labels []attribute.KeyValue, obs ...sdkapi.Observation) {\n\tmm := make([]Measurement, len(obs))\n\tfor i := 0; i < len(obs); i++ {\n\t\to := obs[i]\n\t\tmm[i] = Measurement{\n\t\t\tInstrument: o.AsyncImpl(),\n\t\t\tNumber: o.Number(),\n\t\t}\n\t}\n\tm.collect(context.Background(), labels, mm)\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock()\n\tdefer e.mutex.Unlock()\n\n\tfor _, vec := range e.gauges {\n\t\tvec.Reset()\n\t}\n\n\tdefer func() { ch <- e.up }()\n\n\t// If we fail at any point in retrieving GPU status, we fail 0\n\te.up.Set(1)\n\n\te.GetTelemetryFromNVML()\n\n\tfor _, vec := range e.gauges {\n\t\tvec.Collect(ch)\n\t}\n}", "func (p *statefulSyncInstrument[N, Storage, Methods]) Collect(seq data.Sequence, output *[]data.Instrument) {\n\tp.instLock.Lock()\n\tdefer p.instLock.Unlock()\n\n\tioutput := p.appendInstrument(output)\n\n\tfor set, entry := range p.data {\n\t\tp.appendPoint(ioutput, set, &entry.storage, aggregation.CumulativeTemporality, seq.Start, seq.Now, false)\n\t}\n}", "func (c *transportNodeCollector) Collect(ch chan<- prometheus.Metric) {\n\ttransportNodeMetrics := c.generateTransportNodeMetrics()\n\tfor _, metric := range transportNodeMetrics {\n\t\tch <- metric\n\t}\n}", "func (m *Monitoring) collect() {\n\tfor {\n\t\tevents, ok := <-m.ch\n\t\tif !ok {\n\t\t\tlog.Printf(\"event channel is closed\")\n\t\t\treturn\n\t\t}\n\n\t\tif err := m.w.Write(context.Background(), events); err != nil {\n\t\t\tlog.Printf(\"failed to write metric events %+v: %v\", events, err)\n\t\t}\n\t}\n\n}", "func (o *observer) Collect(ch chan<- prometheus.Metric) {\n\to.updateError.Collect(ch)\n\to.verifyError.Collect(ch)\n\to.expiration.Collect(ch)\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\n\te.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n\n\te.zpool.getStatus()\n\te.poolUsage.Set(float64(e.zpool.capacity))\n\te.providersOnline.Set(float64(e.zpool.online))\n\te.providersFaulted.Set(float64(e.zpool.faulted))\n\n\tch <- e.poolUsage\n\tch <- e.providersOnline\n\tch <- e.providersFaulted\n}", "func (c *Collector) Collect(ch chan<- prometheus.Metric) {\n\tsess, err := sessions.CreateAWSSession()\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn\n\t}\n\n\t// Init WaitGroup. Without a WaitGroup the channel we write\n\t// results to will close before the goroutines finish\n\tvar wg sync.WaitGroup\n\twg.Add(len(c.Scrapers))\n\n\t// Iterate through all scrapers and invoke the scrape\n\tfor _, scraper := range c.Scrapers {\n\t\t// Wrape the scrape invocation in a goroutine, but we need to pass\n\t\t// the scraper into the function explicitly to re-scope the variable\n\t\t// the goroutine accesses. If we don't do this, we can sometimes hit\n\t\t// a case where the scraper reports results twice and the collector panics\n\t\tgo func(scraper *Scraper) {\n\t\t\t// Done call deferred until end of the scrape\n\t\t\tdefer wg.Done()\n\n\t\t\tlog.Debugf(\"Running scrape: %s\", scraper.ID)\n\t\t\tscrapeResults := scraper.Scrape(sess)\n\n\t\t\t// Iterate through scrape results and send the metric\n\t\t\tfor key, results := range scrapeResults {\n\t\t\t\tfor _, result := range results {\n\t\t\t\t\tch <- prometheus.MustNewConstMetric(scraper.Metrics[key].metric, result.Type, result.Value, result.Labels...)\n\t\t\t\t}\n\t\t\t}\n\t\t\tlog.Debugf(\"Scrape completed: %s\", scraper.ID)\n\t\t}(scraper)\n\t}\n\t// Wait\n\twg.Wait()\n}", "func (m *Client) Collect(ch chan<- prometheus.Metric) {\n\tm.storeMu.Lock()\n\tdefer m.storeMu.Unlock()\n\n\tch <- prometheus.MustNewConstMetric(m.storeValuesDesc, prometheus.GaugeValue, float64(len(m.store)))\n\n\tfor k, v := range m.store {\n\t\tch <- prometheus.MustNewConstMetric(m.storeSizesDesc, prometheus.GaugeValue, float64(len(v.value)), k)\n\t}\n}", "func (c *NetSocket) Collect(ctx context.Context) error {\n\tmetrics := cgm.Metrics{}\n\n\tc.Lock()\n\n\tif c.runTTL > time.Duration(0) {\n\t\tif time.Since(c.lastEnd) < c.runTTL {\n\t\t\tc.logger.Warn().Msg(collector.ErrTTLNotExpired.Error())\n\t\t\tc.Unlock()\n\t\t\treturn collector.ErrTTLNotExpired\n\t\t}\n\t}\n\tif c.running {\n\t\tc.logger.Warn().Msg(collector.ErrAlreadyRunning.Error())\n\t\tc.Unlock()\n\t\treturn collector.ErrAlreadyRunning\n\t}\n\n\tc.running = true\n\tc.lastStart = time.Now()\n\tc.Unlock()\n\n\tif err := c.sockstatCollect(ctx, &metrics); err != nil {\n\t\tc.logger.Warn().Err(err).Msg(\"sockstat\")\n\t}\n\n\tc.setStatus(metrics, nil)\n\treturn nil\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\tok := e.collectPeersMetric(ch)\n\tok = e.collectLeaderMetric(ch) && ok\n\tok = e.collectNodesMetric(ch) && ok\n\tok = e.collectMembersMetric(ch) && ok\n\tok = e.collectMembersWanMetric(ch) && ok\n\tok = e.collectServicesMetric(ch) && ok\n\tok = e.collectHealthStateMetric(ch) && ok\n\tok = e.collectKeyValues(ch) && ok\n\n\tif ok {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tup, prometheus.GaugeValue, 1.0,\n\t\t)\n\t} else {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tup, prometheus.GaugeValue, 0.0,\n\t\t)\n\t}\n}", "func (s *Streams) Collect() []interface{} {\n\tdata, ok := s.Buffer.Obj().([]interface{})\n\n\tif !ok {\n\t\treturn nil\n\t}\n\n\ts.Buffer.Clear()\n\treturn data\n}", "func (c *TeamsCollector) Collect(ch chan<- prometheus.Metric) {\n\n\tteams := getTotalTeams()\n\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.totalTeamsGaugeDesc,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(teams),\n\t)\n}", "func coveringFromSpans(spans []roachpb.Span, payload interface{}) intervalccl.Covering {\n\tvar covering intervalccl.Covering\n\tfor _, span := range spans {\n\t\tcovering = append(covering, intervalccl.Range{\n\t\t\tStart: []byte(span.Key),\n\t\t\tEnd: []byte(span.EndKey),\n\t\t\tPayload: payload,\n\t\t})\n\t}\n\treturn covering\n}", "func (c *SecurityGroupCollector) Collect(ch chan<- prometheus.Metric) {\n\tfor _, zone := range affectedZones(c.client) {\n\t\tnow := time.Now()\n\t\tresp, err := c.instance.ListSecurityGroups(&instance.ListSecurityGroupsRequest{\n\t\t\tZone: zone,\n\t\t\tOrganization: c.org,\n\t\t\tProject: c.project,\n\t\t}, scw.WithAllPages())\n\t\tc.duration.WithLabelValues(\"security_group\").Observe(time.Since(now).Seconds())\n\n\t\tif err != nil {\n\t\t\tlevel.Error(c.logger).Log(\n\t\t\t\t\"msg\", \"Failed to fetch security groups\",\n\t\t\t\t\"zone\", zone,\n\t\t\t\t\"err\", err,\n\t\t\t)\n\n\t\t\tc.failures.WithLabelValues(\"security_group\").Inc()\n\t\t\treturn\n\t\t}\n\n\t\tlevel.Debug(c.logger).Log(\n\t\t\t\"msg\", \"Fetched security groups\",\n\t\t\t\"zone\", zone,\n\t\t\t\"count\", resp.TotalCount,\n\t\t)\n\n\t\tfor _, securityGroup := range resp.SecurityGroups {\n\t\t\tvar (\n\t\t\t\tenableDefault float64\n\t\t\t\tprojectDefault float64\n\t\t\t\tstateful float64\n\t\t\t\tinboundDefault float64\n\t\t\t\toutboundDefault float64\n\t\t\t)\n\n\t\t\tlabels := []string{\n\t\t\t\tsecurityGroup.ID,\n\t\t\t\tsecurityGroup.Name,\n\t\t\t\tsecurityGroup.Zone.String(),\n\t\t\t\tsecurityGroup.Organization,\n\t\t\t\tsecurityGroup.Project,\n\t\t\t}\n\n\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\tc.Defined,\n\t\t\t\tprometheus.GaugeValue,\n\t\t\t\t1.0,\n\t\t\t\tlabels...,\n\t\t\t)\n\n\t\t\tif securityGroup.EnableDefaultSecurity {\n\t\t\t\tenableDefault = 1.0\n\t\t\t}\n\n\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\tc.EnableDefault,\n\t\t\t\tprometheus.GaugeValue,\n\t\t\t\tenableDefault,\n\t\t\t\tlabels...,\n\t\t\t)\n\n\t\t\tif securityGroup.ProjectDefault {\n\t\t\t\tprojectDefault = 1.0\n\t\t\t}\n\n\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\tc.ProjectDefault,\n\t\t\t\tprometheus.GaugeValue,\n\t\t\t\tprojectDefault,\n\t\t\t\tlabels...,\n\t\t\t)\n\n\t\t\tif securityGroup.Stateful {\n\t\t\t\tstateful = 1.0\n\t\t\t}\n\n\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\tc.Stateful,\n\t\t\t\tprometheus.GaugeValue,\n\t\t\t\tstateful,\n\t\t\t\tlabels...,\n\t\t\t)\n\n\t\t\tswitch val := securityGroup.InboundDefaultPolicy; val {\n\t\t\tcase instance.SecurityGroupPolicyAccept:\n\t\t\t\tinboundDefault = 1.0\n\t\t\tcase instance.SecurityGroupPolicyDrop:\n\t\t\t\tinboundDefault = 0.0\n\t\t\tdefault:\n\t\t\t\tinboundDefault = 0.0\n\t\t\t}\n\n\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\tc.InboundDefault,\n\t\t\t\tprometheus.GaugeValue,\n\t\t\t\tinboundDefault,\n\t\t\t\tlabels...,\n\t\t\t)\n\n\t\t\tswitch val := securityGroup.OutboundDefaultPolicy; val {\n\t\t\tcase instance.SecurityGroupPolicyAccept:\n\t\t\t\toutboundDefault = 1.0\n\t\t\tcase instance.SecurityGroupPolicyDrop:\n\t\t\t\toutboundDefault = 0.0\n\t\t\tdefault:\n\t\t\t\toutboundDefault = 0.0\n\t\t\t}\n\n\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\tc.OutboundDefault,\n\t\t\t\tprometheus.GaugeValue,\n\t\t\t\toutboundDefault,\n\t\t\t\tlabels...,\n\t\t\t)\n\n\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\tc.Servers,\n\t\t\t\tprometheus.GaugeValue,\n\t\t\t\tfloat64(len(securityGroup.Servers)),\n\t\t\t\tlabels...,\n\t\t\t)\n\n\t\t\tif securityGroup.CreationDate != nil {\n\t\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\t\tc.Created,\n\t\t\t\t\tprometheus.GaugeValue,\n\t\t\t\t\tfloat64(securityGroup.CreationDate.Unix()),\n\t\t\t\t\tlabels...,\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tif securityGroup.ModificationDate != nil {\n\t\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\t\tc.Modified,\n\t\t\t\t\tprometheus.GaugeValue,\n\t\t\t\t\tfloat64(securityGroup.ModificationDate.Unix()),\n\t\t\t\t\tlabels...,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n}", "func (pr *PeriodicReader) collect(ctx context.Context, method func(context.Context, data.Metrics) error) error {\n\tpr.lock.Lock()\n\tdefer pr.lock.Unlock()\n\n\t// The lock ensures that re-use of `pr.data` is successful, it\n\t// means that shutdown, flush, and ordinary collection are\n\t// exclusive. Note that shutdown will cancel a concurrent\n\t// (ordinary) export, while flush will wait for a concurrent\n\t// export.\n\tpr.data = pr.producer.Produce(&pr.data)\n\n\treturn method(ctx, pr.data)\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\tvar (\n\t\tdata *Data\n\t\terr error\n\t)\n\n\te.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n\n\te.resetGaugeVecs() // Clean starting point\n\n\tvar endpointOfAPI []string\n\tif strings.HasSuffix(rancherURL, \"v3\") || strings.HasSuffix(rancherURL, \"v3/\") {\n\t\tendpointOfAPI = endpointsV3\n\t} else {\n\t\tendpointOfAPI = endpoints\n\t}\n\n\tcacheExpired := e.IsCacheExpired()\n\n\t// Range over the pre-configured endpoints array\n\tfor _, p := range endpointOfAPI {\n\t\tif cacheExpired {\n\t\t\tdata, err = e.gatherData(e.rancherURL, e.resourceLimit, e.accessKey, e.secretKey, p, ch)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Error getting JSON from URL %s\", p)\n\t\t\t\treturn\n\t\t\t}\n\t\t\te.cache[p] = data\n\t\t} else {\n\t\t\td, ok := e.cache[p]\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tdata = d\n\t\t}\n\n\t\tif err := e.processMetrics(data, p, e.hideSys, ch); err != nil {\n\t\t\tlog.Errorf(\"Error scraping rancher url: %s\", err)\n\t\t\treturn\n\t\t}\n\t\tlog.Infof(\"Metrics successfully processed for %s\", p)\n\t}\n\n\tif cacheExpired {\n\t\te.RenewCache()\n\t}\n\n\tfor _, m := range e.gaugeVecs {\n\t\tm.Collect(ch)\n\t}\n}", "func (c *DebugFsStatCollector) Collect(ch chan<- prometheus.Metric) {\n\tc.updateProbeStats(0, \"kprobe\", ch)\n\tc.updateProbeStats(0, \"uprobe\", ch)\n}", "func newCollectPacket(s SpanID, as Annotations) *wire.CollectPacket {\n\treturn &wire.CollectPacket{\n\t\tSpanid: s.wire(),\n\t\tAnnotation: as.wire(),\n\t}\n}", "func (c *solarCollector) Collect(ch chan<- prometheus.Metric) {\n\tc.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer c.mutex.Unlock()\n\tif err := c.collect(ch); err != nil {\n\t\tlog.Printf(\"Error getting solar controller data: %s\", err)\n\t\tc.scrapeFailures.Inc()\n\t\tc.scrapeFailures.Collect(ch)\n\t}\n\treturn\n}", "func (ulw *Wrapper) Collect() {\n\tulw.ul.Collect()\n\tsort.Sort(byTotalTime(ulw.ul.Results))\n}", "func (collector *collector) Collect(ch chan<- prometheus.Metric) {\n\tcontainerNames, err := collector.server.GetContainerNames()\n\tif err != nil {\n\t\tcollector.logger.Printf(\"Can't query container names: %s\", err)\n\t\treturn\n\t}\n\n\tfor _, containerName := range containerNames {\n\t\tstate, _, err := collector.server.GetContainerState(containerName)\n\t\tif err != nil {\n\t\t\tcollector.logger.Printf(\n\t\t\t\t\"Can't query container state for `%s`: %s\", containerName, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tcollector.collectContainerMetrics(ch, containerName, state)\n\t}\n}", "func (*noOpConntracker) Collect(ch chan<- prometheus.Metric) {}", "func (c *Collector) Collect(ch chan<- prometheus.Metric) {\n\tc.Lock()\n\tdefer c.Unlock()\n\n\tc.totalScrapes.Inc()\n\terr := c.getDadataBalance()\n\tif err != nil {\n\t\tc.failedBalanceScrapes.Inc()\n\t}\n\terr = c.getDadataStats()\n\tif err != nil {\n\t\tc.failedStatsScrapes.Inc()\n\t}\n\n\tch <- c.totalScrapes\n\tch <- c.failedBalanceScrapes\n\tch <- c.failedStatsScrapes\n\tch <- c.CurrentBalance\n\tch <- c.ServicesClean\n\tch <- c.ServicesMerging\n\tch <- c.ServicesSuggestions\n}", "func (c *SchedulerController) CollectMetrics(ch chan<- prometheus.Metric) {\n\tmetric, err := prometheus.NewConstMetric(scheduler.ControllerWorkerSum, prometheus.GaugeValue, float64(c.RunningWorkers()), \"seed\")\n\tif err != nil {\n\t\tscheduler.ScrapeFailures.With(prometheus.Labels{\"kind\": \"gardener-shoot-scheduler\"}).Inc()\n\t\treturn\n\t}\n\tch <- metric\n}", "func (b Blackbox) Collect(metrics chan<- prometheus.Metric) {\n\tb.fetchReferenceDiscoveryMetrics.Collect(metrics)\n\tb.httpPostMetrics.Collect(metrics)\n\tb.wantedRefs.Collect(metrics)\n}", "func (c *StorageDomainCollector) Collect(ch chan<- prometheus.Metric) {\n\tctx, span := c.cc.Tracer().Start(c.rootCtx, \"StorageDomainCollector.Collect\")\n\tdefer span.End()\n\n\tc.cc.SetMetricsCh(ch)\n\n\ttimer := prometheus.NewTimer(c.collectDuration)\n\tdefer timer.ObserveDuration()\n\n\ts := StorageDomains{}\n\terr := c.cc.Client().GetAndParse(ctx, \"storagedomains\", &s)\n\tif err != nil {\n\t\tc.cc.HandleError(err, span)\n\t\treturn\n\t}\n\n\tfor _, h := range s.Domains {\n\t\tc.collectMetricsForDomain(h)\n\t}\n}", "func (sc *SlurmCollector) Collect(ch chan<- prometheus.Metric) {\n\tsc.mutex.Lock()\n\tdefer sc.mutex.Unlock()\n\n\tlog.Debugf(\"Time since last scrape: %f seconds\", time.Since(sc.lastScrape).Seconds())\n\tif time.Since(sc.lastScrape).Seconds() > float64(sc.scrapeInterval) {\n\t\tsc.updateDynamicJobIds()\n\t\tvar err error\n\t\tsc.sshClient, err = sc.sshConfig.NewClient()\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Creating SSH client: %s\", err.Error())\n\t\t\treturn\n\t\t}\n\t\tdefer sc.sshClient.Close()\n\t\tlog.Infof(\"Collecting metrics from Slurm...\")\n\t\tsc.trackedJobs = make(map[string]bool)\n\t\tif sc.targetJobIds == \"\" {\n\t\t\t// sc.collectQueue()\n\t\t} else {\n\t\t\tsc.collectAcct()\n\t\t}\n\t\tif !sc.skipInfra {\n\t\t\tsc.collectInfo()\n\t\t}\n\t\tsc.lastScrape = time.Now()\n\t\tsc.delJobs()\n\n\t}\n\n\tsc.updateMetrics(ch)\n}", "func (c *ClusterManager) Collect(ch chan<- prometheus.Metric) {\n\toomCountByHost, ramUsageByHost := c.ReallyExpensiveAssessmentOfTheSystemState()\n\tfor host, oomCount := range oomCountByHost {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.OOMCountDesc,\n\t\t\tprometheus.CounterValue,\n\t\t\tfloat64(oomCount),\n\t\t\thost,\n\t\t)\n\t}\n\tfor host, ramUsage := range ramUsageByHost {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.RAMUsageDesc,\n\t\t\tprometheus.GaugeValue,\n\t\t\tramUsage,\n\t\t\thost,\n\t\t)\n\t}\n}", "func (c *DiskCache) Collect(metrics chan<- prometheus.Metric) {\n\tc.requestTotals.Collect(metrics)\n\tc.missTotals.Collect(metrics)\n\tc.bytesStoredtotals.Collect(metrics)\n\tc.bytesFetchedtotals.Collect(metrics)\n\tc.bytesLoserTotals.Collect(metrics)\n\tc.errTotal.Collect(metrics)\n\tc.walkerRemovalTotal.Collect(metrics)\n\tc.walkerErrorTotal.Collect(metrics)\n\tc.walkerEmptyDirTotal.Collect(metrics)\n\tc.walkerEmptyDirRemovalTotal.Collect(metrics)\n}", "func (e *Route53Exporter) CollectLoop() {\n\tclient := awsclient.NewClientFromSession(e.sess)\n\n\tfor {\n\t\tctx, ctxCancelFunc := context.WithTimeout(context.Background(), e.timeout)\n\t\te.Cancel = ctxCancelFunc\n\t\tlevel.Info(e.logger).Log(\"msg\", \"Updating Route53 metrics...\")\n\n\t\thostedZones, err := getAllHostedZones(client, ctx, e.logger)\n\n\t\tlevel.Info(e.logger).Log(\"msg\", \"Got all zones\")\n\t\tif err != nil {\n\t\t\tlevel.Error(e.logger).Log(\"msg\", \"Could not retrieve the list of hosted zones\", \"error\", err.Error())\n\t\t\tawsclient.AwsExporterMetrics.IncrementErrors()\n\t\t}\n\n\t\terr = e.getHostedZonesPerAccountMetrics(client, hostedZones, ctx)\n\t\tif err != nil {\n\t\t\tlevel.Error(e.logger).Log(\"msg\", \"Could not get limits for hosted zone\", \"error\", err.Error())\n\t\t\tawsclient.AwsExporterMetrics.IncrementErrors()\n\t\t}\n\n\t\terrs := e.getRecordsPerHostedZoneMetrics(client, hostedZones, ctx)\n\t\tfor _, err = range errs {\n\t\t\tlevel.Error(e.logger).Log(\"msg\", \"Could not get limits for hosted zone\", \"error\", err.Error())\n\t\t\tawsclient.AwsExporterMetrics.IncrementErrors()\n\t\t}\n\n\t\tlevel.Info(e.logger).Log(\"msg\", \"Route53 metrics Updated\")\n\n\t\tctxCancelFunc() // should never do anything as we don't run stuff in the background\n\n\t\ttime.Sleep(e.interval)\n\t}\n}", "func (c *Client) Collect(ch chan<- prometheus.Metric) {\n\tc.metrics.functionInvocation.Collect(ch)\n\tc.metrics.functionsHistogram.Collect(ch)\n\tc.metrics.queueHistogram.Collect(ch)\n\tc.metrics.functionInvocationStarted.Collect(ch)\n\tc.metrics.serviceReplicasGauge.Reset()\n\tfor _, service := range c.services {\n\t\tvar serviceName string\n\t\tif len(service.Namespace) > 0 {\n\t\t\tserviceName = fmt.Sprintf(\"%s.%s\", service.Name, service.Namespace)\n\t\t} else {\n\t\t\tserviceName = service.Name\n\t\t}\n\t\tc.metrics.serviceReplicasGauge.\n\t\t\tWithLabelValues(serviceName).\n\t\t\tSet(float64(service.Replicas))\n\t}\n\tc.metrics.serviceReplicasGauge.Collect(ch)\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock()\n\tdefer e.mutex.Unlock()\n\n\te.scrape()\n\n\te.up.Collect(ch)\n\te.totalScrapes.Collect(ch)\n\te.exchangeStatus.Collect(ch)\n\te.ltp.Collect(ch)\n\te.bestBid.Collect(ch)\n\te.bestAsk.Collect(ch)\n\te.bestBidSize.Collect(ch)\n\te.bestAskSize.Collect(ch)\n\te.totalBidDepth.Collect(ch)\n\te.totalAskDepth.Collect(ch)\n\te.volume.Collect(ch)\n\te.volumeByProduct.Collect(ch)\n}", "func (o *OSDCollector) Collect(ch chan<- prometheus.Metric) {\n\tif err := o.collectOSDPerf(); err != nil {\n\t\tlog.Println(\"failed collecting osd perf stats:\", err)\n\t}\n\n\tif err := o.collectOSDDump(); err != nil {\n\t\tlog.Println(\"failed collecting osd dump:\", err)\n\t}\n\n\tif err := o.collectOSDDF(); err != nil {\n\t\tlog.Println(\"failed collecting osd metrics:\", err)\n\t}\n\n\tif err := o.collectOSDTreeDown(ch); err != nil {\n\t\tlog.Println(\"failed collecting osd metrics:\", err)\n\t}\n\n\tfor _, metric := range o.collectorList() {\n\t\tmetric.Collect(ch)\n\t}\n\n\tif err := o.collectOSDScrubState(ch); err != nil {\n\t\tlog.Println(\"failed collecting osd scrub state:\", err)\n\t}\n}", "func (c *MetricsCollector) Collect(ch chan<- prometheus.Metric) {\n\tfor _, s := range c.status {\n\t\ts.RLock()\n\t\tdefer s.RUnlock()\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.verify,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(s.VerifyRestore),\n\t\t\t\"verify_restore\",\n\t\t\ts.BackupService,\n\t\t\ts.StorageService,\n\t\t)\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.verify,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(s.VerifyDiff),\n\t\t\t\"verify_diff\",\n\t\t\ts.BackupService,\n\t\t\ts.StorageService,\n\t\t)\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tc.verify,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(s.VerifyChecksum),\n\t\t\t\"verify_checksum\",\n\t\t\ts.BackupService,\n\t\t\ts.StorageService,\n\t\t)\n\t}\n\n}" ]
[ "0.6309139", "0.62056905", "0.59496146", "0.5861292", "0.58595854", "0.5749108", "0.5731653", "0.57281625", "0.56668395", "0.5666777", "0.5659342", "0.5649344", "0.55813223", "0.55552435", "0.55202997", "0.55081296", "0.54767895", "0.54767895", "0.54666686", "0.545717", "0.5450747", "0.54505527", "0.544508", "0.5440054", "0.5439095", "0.5422174", "0.53877944", "0.5386716", "0.53777814", "0.53743565", "0.53377837", "0.53343785", "0.5320144", "0.5298158", "0.52956486", "0.52869594", "0.5279735", "0.52791387", "0.52758926", "0.52631927", "0.5262825", "0.52571845", "0.52527297", "0.5251159", "0.5246382", "0.5242903", "0.52254933", "0.52246296", "0.52175575", "0.5197544", "0.5189173", "0.5188942", "0.51804596", "0.51629144", "0.5159724", "0.51348174", "0.5119232", "0.5117924", "0.51175076", "0.5112991", "0.5110002", "0.5108095", "0.51069033", "0.5102488", "0.5080886", "0.5054106", "0.5051215", "0.50400865", "0.503956", "0.50385106", "0.50333095", "0.50085443", "0.500604", "0.5005395", "0.5001058", "0.4979235", "0.49773383", "0.49750885", "0.49744478", "0.49652916", "0.49633992", "0.4960799", "0.4959177", "0.4948116", "0.49430653", "0.49333423", "0.49192643", "0.4918806", "0.49164122", "0.49072838", "0.4902036", "0.4894147", "0.48747724", "0.48743692", "0.48741183", "0.48666382", "0.485854", "0.48560983", "0.48530197", "0.48430637" ]
0.7222805
0
Flush immediately sends all pending spans to the underlying collector.
Flush сразу отправляет все ожидающие спаны внизу лежащему собирателю.
func (cc *ChunkedCollector) Flush() error { cc.mu.Lock() pendingBySpanID := cc.pendingBySpanID pending := cc.pending cc.pendingBySpanID = nil cc.pending = nil cc.mu.Unlock() var errs []error for _, spanID := range pending { p := pendingBySpanID[spanID] if err := cc.Collector.Collect(spanIDFromWire(p.Spanid), annotationsFromWire(p.Annotation)...); err != nil { errs = append(errs, err) } } if len(errs) == 1 { return errs[0] } else if len(errs) > 1 { return fmt.Errorf("ChunkedCollector: multiple errors: %v", errs) } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s *Collector) Flush() error {\n\treturn s.flusher.Flush(s.stats)\n}", "func (c *HTTPCollector) flush(b []*zipkincore.Span) (err error) {\n\tdefer func() {\n\t\tc.batchPool.Put(b[:0])\n\t\tif err != nil {\n\t\t\tc.logger.Log(\"err\", err)\n\t\t}\n\t}()\n\n\t// Do not send an empty batch\n\tif len(b) == 0 {\n\t\treturn nil\n\t}\n\n\tdata, err := httpSerialize(b)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar req *http.Request\n\n\treq, err = http.NewRequest(\"POST\", c.url, data)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/x-thrift\")\n\tif _, err = c.client.Do(req); err != nil {\n\t\treturn\n\t}\n\n\treturn nil\n}", "func (c *Collector) Flush() {\n\tclose(c.results)\n\t<-c.done\n}", "func (c *Stats) Flush() {\n\t// Add a job to the flush wait group\n\tc.flushWG.Add(1)\n\tc.jobs <- &job{flush: true}\n\tc.flushWG.Wait()\n}", "func (w *batchWriter) Flush(ctx context.Context) error {\n\tfor i, s := range w.batch {\n\t\t_, err := fmt.Fprintln(w.writer, s)\n\t\tif err != nil {\n\t\t\tw.batch = w.batch[i:]\n\t\t\tw.persistRecords = w.persistRecords[i:]\n\t\t\treturn err\n\t\t}\n\t\tw.flushed = w.persistRecords[i]\n\t}\n\tw.batch = make([]string, 0, batchSize)\n\tw.persistRecords = make([]*persistRecord, 0, batchSize)\n\treturn nil\n}", "func Flush() {\n\tif t, ok := internal.GetGlobalTracer().(*tracer); ok {\n\t\tt.flushSync()\n\t}\n}", "func (e *Exporter) Flush() {\n\te.tracer.Flush(context.Background())\n}", "func (f *flusher) Flush() {\n\tf.mu.Lock()\n\tfor _, m := range f.meters {\n\t\tm.FlushReading(f.sink)\n\t}\n\tf.sink.Flush()\n\tf.mu.Unlock()\n}", "func Flush() {\n\tif traceListeners != nil {\n\t\tfor _, tl := range traceListeners {\n\t\t\t(*tl).Flush()\n\t\t}\n\t}\n}", "func (fl *flusher) Flush(ctx context.Context, span opentracing.Span, classrooms []models.Classroom) []models.Classroom {\n\n\tchunks, err := utils.SplitSlice(classrooms, fl.chunkSize)\n\n\tif err != nil {\n\t\treturn classrooms\n\t}\n\n\tfor i, chunk := range chunks {\n\n\t\tvar childSpan opentracing.Span\n\t\tif span != nil {\n\t\t\tchildSpan = opentracing.StartSpan(\"Flush\", opentracing.ChildOf(span.Context()))\n\t\t}\n\n\t\t_, err := fl.repo.MultiAddClassroom(ctx, chunk)\n\n\t\tif span != nil {\n\n\t\t\tchildSpan.LogFields(\n\t\t\t\tlog.Int(\"len\", len(chunk)),\n\t\t\t\tlog.Bool(\"sent\", err == nil),\n\t\t\t)\n\t\t\tchildSpan.Finish()\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn classrooms[fl.chunkSize*i:]\n\t\t}\n\t}\n\n\treturn nil\n}", "func (buf *Buffer) Flush(now time.Time) {\n\tbatch := buf.currentBatch\n\tif batch == nil {\n\t\treturn\n\t}\n\n\tbatch.nextSend = now // immediately make available to send\n\tbuf.unleased.PushBatch(batch)\n\tbuf.batchItemsGuess.record(batch.countedItems)\n\tbuf.currentBatch = nil\n\treturn\n}", "func (c *Client) flush() {\n\tsubmissions := make([]*Request, 0, len(c.requests)+1)\n\tif c.newMetrics {\n\t\tc.newMetrics = false\n\t\tr := c.newRequest(RequestTypeGenerateMetrics)\n\t\tpayload := &Metrics{\n\t\t\tNamespace: c.Namespace,\n\t\t\tLibLanguage: \"go\",\n\t\t\tLibVersion: version.Tag,\n\t\t}\n\t\tfor _, m := range c.metrics {\n\t\t\ts := Series{\n\t\t\t\tMetric: m.name,\n\t\t\t\tType: string(m.kind),\n\t\t\t\tTags: m.tags,\n\t\t\t\tCommon: m.common,\n\t\t\t}\n\t\t\ts.Points = [][2]float64{{m.ts, m.value}}\n\t\t\tpayload.Series = append(payload.Series, s)\n\t\t}\n\t\tr.Payload = payload\n\t\tsubmissions = append(submissions, r)\n\t}\n\n\t// copy over requests so we can do the actual submission without holding\n\t// the lock. Zero out the old stuff so we don't leak references\n\tfor i, r := range c.requests {\n\t\tsubmissions = append(submissions, r)\n\t\tc.requests[i] = nil\n\t}\n\tc.requests = c.requests[:0]\n\n\tgo func() {\n\t\tfor _, r := range submissions {\n\t\t\terr := c.submit(r)\n\t\t\tif err != nil {\n\t\t\t\tc.log(\"telemetry submission failed: %s\", err)\n\t\t\t}\n\t\t}\n\t}()\n}", "func (b *Buffer) Flush() {\n\tif len(b.series) == 0 {\n\t\treturn\n\t}\n\n\tsbuffer := []*influxdb.Series{}\n\tfor _, item := range b.series {\n\t\tsbuffer = append(sbuffer, item)\n\t}\n\n\tb.fn(sbuffer)\n\tb.Clear()\n}", "func (clt *Client) flush() {\n\tif !clt.timer.Stop() {\n\t\tselect {\n\t\tcase <-clt.timer.C:\n\t\tdefault:\n\t\t}\n\t}\n\tclt.timer.Reset(recordsTimeout)\n\n\t// Don't send empty batch\n\tif len(clt.batch) == 0 {\n\t\treturn\n\t}\n\n\tclt.putRecordBatch()\n\n\tclt.batchSize = 0\n\tclt.batch = nil\n}", "func (t *tracer) flushSync() {\n\tdone := make(chan struct{})\n\tt.flush <- done\n\t<-done\n}", "func (b *Basic) flush(done chan<- struct{}) {\n\tfor {\n\t\tvar rec *LogRec\n\t\tvar err error\n\t\tselect {\n\t\tcase rec = <-b.in:\n\t\t\t// ignore any redundant flush records.\n\t\t\tif rec.flush == nil {\n\t\t\t\terr = b.w.Write(rec)\n\t\t\t\tif err != nil {\n\t\t\t\t\tb.incErrorCounter()\n\t\t\t\t\trec.Logger().Logr().ReportError(err)\n\t\t\t\t}\n\t\t\t}\n\t\tdefault:\n\t\t\tdone <- struct{}{}\n\t\t\treturn\n\t\t}\n\t}\n}", "func (lms *MessageSorter) Flush() {\n\tsort.Sort(ktail.ByTimestamp(lms.cache))\n\n\tfor _, msg := range lms.cache {\n\t\tlms.format(lms.wr, msg)\n\t}\n\n\tlms.cache = []*ktail.LogMessage{}\n\tlms.current = 0\n}", "func (e *eventDebouncer) flush() {\n\tif len(e.events) == 0 {\n\t\treturn\n\t}\n\n\t// if the flush interval is faster than the callback then we will end up calling\n\t// the callback multiple times, probably a bad idea. In this case we could drop\n\t// frames?\n\tgo e.callback(e.events)\n\te.events = make([]frame, 0, eventBufferSize)\n}", "func (b *FlushingBatch) Flush() error {\n\terr := b.index.Batch(b.batch)\n\tif err != nil {\n\t\treturn err\n\t}\n\tb.batch = b.index.NewBatch()\n\treturn nil\n}", "func (q *Queue) Flush() {\r\n\tel, _ := q.clear()\r\n\r\n\tfor el != nil {\r\n\t\tq.cb(el.v)\r\n\t\tel = el.next\r\n\t}\r\n}", "func (self *averageCache) flush(flushLimit int) {\n\tlog.WithFields(log.Fields{\n\t\t\"cache\": self.name,\n\t}).Debug(\"Internal Flush\")\n\tvar valueFlushTargets []*whisper.TimeSeriesPoint = make([]*whisper.TimeSeriesPoint, 0)\n\tvar countFlushTargets []*whisper.TimeSeriesPoint = make([]*whisper.TimeSeriesPoint, 0)\n\tfor timeSlot, cacheSlot := range self.cache {\n\t\t// TODO: \n\t\t// Write all changes to subscriptions\n\t\tif cacheSlot.LastUpdated <= flushLimit {\n\t\t\tvalueFlushTargets = append(valueFlushTargets, &whisper.TimeSeriesPoint{timeSlot, cacheSlot.Value})\n\t\t\tcountFlushTargets = append(countFlushTargets, &whisper.TimeSeriesPoint{timeSlot, cacheSlot.Count})\n\t\t\tdelete(self.cache, timeSlot)\n\t\t}\n\t}\n\tlog.Debug(\"FlushAverages: \", valueFlushTargets)\n\tlog.Debug(\"FlushCounts: \", countFlushTargets)\n\n\t// TODO: Write flush targets to whisper\n\t// In another fiber perhaps to make this non-blocking?\n\tself.valueBackend.Write(valueFlushTargets)\n\tself.countBackend.Write(countFlushTargets)\n}", "func (s *Spooler) flush() {\n\tif len(s.spool) > 0 {\n\t\t// copy buffer\n\t\ttmpCopy := make([]*input.FileEvent, len(s.spool))\n\t\tcopy(tmpCopy, s.spool)\n\n\t\t// clear buffer\n\t\ts.spool = s.spool[:0]\n\n\t\t// send\n\t\ts.publisher <- tmpCopy\n\t}\n\ts.nextFlushTime = time.Now().Add(s.idleTimeout)\n}", "func (clt *Client) flush() {\n\n\tif !clt.t.Stop() {\n\t\tselect {\n\t\tcase <-clt.t.C:\n\t\tdefault:\n\t\t}\n\t}\n\tclt.t.Reset(recordsTimeout)\n\n\tsize := len(clt.batch)\n\t// Don't send empty batch\n\tif size == 0 {\n\t\treturn\n\t}\n\n\t// Create slice with the struct need by firehose\n\tfor _, b := range clt.batch {\n\t\tclt.records = append(clt.records, &firehose.Record{Data: b.B})\n\t}\n\n\t// Create the request\n\treq, _ := clt.srv.awsSvc.PutRecordBatchRequest(&firehose.PutRecordBatchInput{\n\t\tDeliveryStreamName: aws.String(clt.srv.cfg.StreamName),\n\t\tRecords: clt.records,\n\t})\n\n\t// Add context timeout to the request\n\tctx, cancel := context.WithTimeout(context.Background(), connectTimeout)\n\tdefer cancel()\n\n\treq.SetContext(ctx)\n\n\t// Send the request\n\terr := req.Send()\n\tif err != nil {\n\t\tif req.IsErrorThrottle() {\n\t\t\tlog.Printf(\"Firehose client %s [%d]: ERROR IsErrorThrottle: %s\", clt.srv.cfg.StreamName, clt.ID, err)\n\t\t} else {\n\t\t\tlog.Printf(\"Firehose client %s [%d]: ERROR PutRecordBatch->Send: %s\", clt.srv.cfg.StreamName, clt.ID, err)\n\t\t}\n\t\tclt.srv.failure()\n\n\t\t// Finish if is not critical stream\n\t\tif clt.srv.cfg.Critical {\n\t\t\tlog.Printf(\"Firehose client %s [%d]: ERROR Critical records lost, %d messages lost\", clt.srv.cfg.StreamName, clt.ID, size)\n\t\t}\n\t}\n\n\t// Put slice bytes in the pull after sent\n\tfor _, b := range clt.batch {\n\t\tpool.Put(b)\n\t}\n\n\tclt.batchSize = 0\n\tclt.count = 0\n\tclt.batch = nil\n\tclt.records = nil\n}", "func (sr *SpanRecorder) ForceFlush(context.Context) error {\n\treturn nil\n}", "func flushMetrics(flushChannel chan Metric, finishChannel chan int) {\n\n\tfor {\n\t\tselect {\n\t\tcase metric := <-flushChannel:\n\t\t\tsendMetricToStats(metric)\n\t\tcase <-finishChannel:\n\t\t\treturn\n\t\t}\n\t}\n}", "func (c Consumer) flush() {\n\tfor i := 0; i < MAX_NUM_WIDGETS; i++ {\n\t\t<- c.ch\n\t\tlog.Print(\"Consumer: Recieving from channel assigned to consumer: \", c.id)\n\t}\n}", "func (a *AppTracer) Flush() {\n\tfor _, cli := range a.ClientList {\n\t\tcli.Flush()\n\t}\n}", "func (c *Concentrator) Flush(force bool) *pb.StatsPayload {\n\treturn c.flushNow(time.Now().UnixNano(), force)\n}", "func (oq *outputQueue) flush() error {\n\tif oq.rowIdx <= 0 {\n\t\treturn nil\n\t}\n\tif oq.ep.needExportToFile() {\n\t\tif err := exportDataToCSVFile(oq); err != nil {\n\t\t\tlogError(oq.ses, oq.ses.GetDebugString(),\n\t\t\t\t\"Error occurred while exporting to CSV file\",\n\t\t\t\tzap.Error(err))\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\t//send group of row\n\t\tif oq.showStmtType == ShowTableStatus {\n\t\t\toq.rowIdx = 0\n\t\t\treturn nil\n\t\t}\n\n\t\tif err := oq.proto.SendResultSetTextBatchRowSpeedup(oq.mrs, oq.rowIdx); err != nil {\n\t\t\tlogError(oq.ses, oq.ses.GetDebugString(),\n\t\t\t\t\"Flush error\",\n\t\t\t\tzap.Error(err))\n\t\t\treturn err\n\t\t}\n\t}\n\toq.rowIdx = 0\n\treturn nil\n}", "func (i *queueIndex) flush() error {\n\treturn i.indexArena.Flush(syscall.MS_SYNC)\n}", "func (p *AutoCommitter) Flush() error {\n\tif p.verbose {\n\t\tlog.Info(fmt.Sprintf(\"AutoCommitter-%s(%s) a new flush is comming\", p.name, p.coll))\n\t}\n\tfor _, w := range p.workers {\n\t\tw.flushC <- struct{}{}\n\t\t<-w.flushAckC // wait for completion\n\t}\n\tif p.verbose {\n\t\tlog.Info(fmt.Sprintf(\"AutoCommitter-%s(%s) a new flush is finished\", p.name, p.coll))\n\t}\n\treturn nil\n}", "func (s *ServerlessTraceAgent) Flush() {\n\tif s.Get() != nil {\n\t\ts.ta.FlushSync()\n\t}\n}", "func (c *Client) Flush() error {\n\tif len(c.data) > 0 {\n\t\tc.logger.Infof(\"Pushing metrics: %d\", len(c.data))\n\n\t\tinput := &cloudwatch.PutMetricDataInput{\n\t\t\tNamespace: aws.String(c.namespace),\n\t\t\tMetricData: c.data,\n\t\t}\n\n\t\t_, err := c.svc.PutMetricData(input)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tc.data = nil\n\t}\n\n\treturn nil\n}", "func (t *tracer) worker(tick <-chan time.Time) {\n\tfor {\n\t\tselect {\n\t\tcase trace := <-t.out:\n\t\t\tt.sampleFinishedTrace(trace)\n\t\t\tif len(trace.spans) != 0 {\n\t\t\t\tt.traceWriter.add(trace.spans)\n\t\t\t}\n\t\tcase <-tick:\n\t\t\tt.config.statsd.Incr(\"datadog.tracer.flush_triggered\", []string{\"reason:scheduled\"}, 1)\n\t\t\tt.traceWriter.flush()\n\n\t\tcase done := <-t.flush:\n\t\t\tt.config.statsd.Incr(\"datadog.tracer.flush_triggered\", []string{\"reason:invoked\"}, 1)\n\t\t\tt.traceWriter.flush()\n\t\t\t// TODO(x): In reality, the traceWriter.flush() call is not synchronous\n\t\t\t// when using the agent traceWriter. However, this functionnality is used\n\t\t\t// in Lambda so for that purpose this mechanism should suffice.\n\t\t\tdone <- struct{}{}\n\n\t\tcase <-t.stop:\n\t\tloop:\n\t\t\t// the loop ensures that the payload channel is fully drained\n\t\t\t// before the final flush to ensure no traces are lost (see #526)\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase trace := <-t.out:\n\t\t\t\t\tt.sampleFinishedTrace(trace)\n\t\t\t\t\tif len(trace.spans) != 0 {\n\t\t\t\t\t\tt.traceWriter.add(trace.spans)\n\t\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\tbreak loop\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n}", "func (c *Converter) flush(ctx context.Context, pLogs pdata.Logs) error {\n\tdoneChan := ctx.Done()\n\n\tselect {\n\tcase <-doneChan:\n\t\treturn fmt.Errorf(\"flushing log entries interrupted, err: %w\", ctx.Err())\n\n\tcase c.pLogsChan <- pLogs:\n\n\t// The converter has been stopped so bail the flush.\n\tcase <-c.stopChan:\n\t\treturn errors.New(\"logs converter has been stopped\")\n\t}\n\n\treturn nil\n}", "func (s *shard) Flush() (err error) {\n\t// another flush process is running\n\tif !s.isFlushing.CAS(false, true) {\n\t\treturn nil\n\t}\n\t// 1. mark flush job doing\n\ts.flushCondition.Add(1)\n\n\tdefer func() {\n\t\t//TODO add commit kv meta after ack successfully\n\t\t// mark flush job complete, notify\n\t\ts.flushCondition.Done()\n\t\ts.isFlushing.Store(false)\n\t}()\n\n\t//FIXME stone1100\n\t// index flush\n\tif s.indexDB != nil {\n\t\tif err = s.indexDB.Flush(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// flush memory database if need flush\n\tfor _, memDB := range s.families {\n\t\t//TODO add time threshold???\n\t\tif memDB.MemSize() > constants.ShardMemoryUsedThreshold {\n\t\t\tif err := s.flushMemoryDatabase(memDB); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t}\n\t//FIXME(stone1100) need remove memory database if long time no data\n\t// finally, commit replica sequence\n\ts.ackReplicaSeq()\n\treturn nil\n}", "func (b *httpBatch) Flush() error {\n\treturn nil\n}", "func (th *telemetryHandle) Flush() {\n\tth.client.Channel().Flush()\n}", "func (a *Agent) flush() {\n\tvar wg sync.WaitGroup\n\n\twg.Add(len(a.Config.Processors))\n\tfor _, p := range a.Config.Processors {\n\t\tgo func(processor *models.RunningProcessor) {\n\t\t\tdefer wg.Done()\n\t\t\tprocessor.Flush()\n\t\t}(p)\n\t}\n\n\twg.Add(len(a.Config.Sinks))\n\tfor _, s := range a.Config.Sinks {\n\t\tgo func(sink *models.RunningSink) {\n\t\t\tdefer wg.Done()\n\t\t\terr := sink.Write()\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"ERROR Error writing to sink [%s]: %s\",\n\t\t\t\t\tsink.Name(), err.Error())\n\t\t\t}\n\t\t}(s)\n\t}\n\n\twg.Wait()\n}", "func (cs *UnsafeCounterIndex) Flush(s Counters) Counters {\n\ts = append(s, cs.counters...)\n\tcs.counters.Zero()\n\treturn s\n}", "func (p *Pool) flush() {\n\tconn := p.Pool.Get()\n\tdefer conn.Close()\n\n\tconn.Send(\"DEBUG\", \"FLUSHALL\")\n}", "func (qs *queuedSender) Flush(params *map[string]string) {\n\tvar anonService interface{} = qs\n\tservice, ok := anonService.(types.Service)\n\tif ok {\n\t\t// Since this method is supposed to be deferred we just have to ignore errors\n\t\t_ = service.Send(strings.Join(qs.queue, \"\\n\"), params)\n\t}\n}", "func (ab *Buffer) unsafeFlushAsync(ctx context.Context, contents []interface{}) {\n\tif len(contents) == 0 {\n\t\treturn\n\t}\n\tif ab.Tracer != nil {\n\t\tfinisher := ab.Tracer.StartQueueFlush(ctx)\n\t\tdefer finisher.Finish(nil)\n\t}\n\tif ab.Stats != nil {\n\t\tab.maybeStatCount(ctx, MetricFlush, 1)\n\t\tab.maybeStatGauge(ctx, MetricFlushQueueLength, float64(len(ab.flushes)))\n\t\tab.maybeStatCount(ctx, MetricFlushItemCount, len(contents))\n\t\tstart := time.Now().UTC()\n\t\tdefer func() {\n\t\t\tab.maybeStatElapsed(ctx, MetricFlushEnqueueElapsed, start)\n\t\t}()\n\t}\n\n\tlogger.MaybeDebugf(ab.Log, \"autoflush buffer; queue flush, queue length: %d\", len(ab.flushes))\n\tab.flushes <- Flush{\n\t\tContext: ctx,\n\t\tContents: contents,\n\t}\n}", "func (runner *runner) Flush() error {\n\trunner.mu.Lock()\n\tdefer runner.mu.Unlock()\n\treturn runner.ipvsHandle.Flush()\n}", "func (n *NodeEventsBatcher) Flush() {\n\tvar hasCreate bool\n\toutput := &NodeChangeEventWithInfo{}\n\tfor _, e := range n.buffer {\n\t\tif e.Type == tree.NodeChangeEvent_CREATE {\n\t\t\thasCreate = true\n\t\t}\n\t\toutput.Source = e.Source\n\t\toutput.Type = e.Type\n\t\tif output.Target != nil {\n\t\t\t// Merge metadatas\n\t\t\toutput.Target.Etag = e.Target.Etag\n\t\t\toutput.Target.Type = e.Target.Type\n\t\t\toutput.Target.MTime = e.Target.MTime\n\t\t\toutput.Target.Size = e.Target.Size\n\t\t\tfor k, v := range e.Target.MetaStore {\n\t\t\t\toutput.Target.MetaStore[k] = v\n\t\t\t}\n\t\t} else {\n\t\t\toutput.Target = e.Target\n\t\t}\n\t}\n\tif hasCreate {\n\t\toutput.Type = tree.NodeChangeEvent_CREATE\n\t\toutput.refreshTarget = false\n\t} else {\n\t\toutput.refreshTarget = true\n\t}\n\tn.out <- output\n\tn.done <- n.uuid\n}", "func (i *Batch) flush(ctx context.Context, workerID int, tasks map[string]TaskArgs) {\n\targs := make(map[string]map[string]interface{}, len(tasks))\n\tfor _, task := range tasks {\n\t\targs[task.ID] = task.Args\n\t}\n\trespData, err := i.doFn(ctx, args)\n\tfor _, task := range tasks {\n\t\tgo func(t TaskArgs) {\n\t\t\tt.RespChan <- &TaskResp{\n\t\t\t\tErr: err,\n\t\t\t\tData: respData[t.ID],\n\t\t\t}\n\t\t}(task)\n\t}\n\treturn\n}", "func (a *Agent) flush() {\n\tif len(a.Buf) != 0 {\n\t\ta.Sketch.insert(agentConfig, a.Buf)\n\t\ta.Buf = nil\n\t}\n\n\tif len(a.CountBuf) != 0 {\n\t\ta.Sketch.insertCounts(agentConfig, a.CountBuf)\n\t\ta.CountBuf = nil\n\t}\n}", "func (r *httpReporter) sendBatch() error {\n\t// Select all current spans in the batch to be sent\n\tr.batchMtx.Lock()\n\tsendBatch := r.batch[:]\n\tr.batchMtx.Unlock()\n\n\tif len(sendBatch) == 0 {\n\t\treturn nil\n\t}\n\n\tbody, err := r.serializer.Serialize(sendBatch)\n\tif err != nil {\n\t\tr.logger.Printf(\"failed when marshalling the spans batch: %s\\n\", err.Error())\n\t\treturn err\n\t}\n\n\treq, err := http.NewRequest(\"POST\", r.url, bytes.NewReader(body))\n\tif err != nil {\n\t\tr.logger.Printf(\"failed when creating the request: %s\\n\", err.Error())\n\t\treturn err\n\t}\n\treq.Header.Set(\"Content-Type\", r.serializer.ContentType())\n\tif r.reqCallback != nil {\n\t\tr.reqCallback(req)\n\t}\n\n\tctx, cancel := context.WithTimeout(req.Context(), r.reqTimeout)\n\tdefer cancel()\n\n\tresp, err := r.client.Do(req.WithContext(ctx))\n\tif err != nil {\n\t\tr.logger.Printf(\"failed to send the request: %s\\n\", err.Error())\n\t\treturn err\n\t}\n\t_ = resp.Body.Close()\n\tif resp.StatusCode < 200 || resp.StatusCode > 299 {\n\t\tr.logger.Printf(\"failed the request with status code %d\\n\", resp.StatusCode)\n\t}\n\n\t// Remove sent spans from the batch even if they were not saved\n\tr.batchMtx.Lock()\n\tr.batch = r.batch[len(sendBatch):]\n\tr.batchMtx.Unlock()\n\n\treturn nil\n}", "func (s *PrometheusSerializer) Flush() error {\n\twr := &prompb.WriteRequest{\n\t\tTimeseries: s.series[:s.cur],\n\t}\n\tdata, err := wr.Marshal()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsb := bytebufferpool.Get()\n\tsb.B = snappy.Encode(sb.B, data)\n\n\tvar sizeBuf []byte\n\tsizeBuf = marshalUint64(sizeBuf[:0], uint64(sb.Len()))\n\tif _, err := s.w.Write(sizeBuf); err != nil {\n\t\tbytebufferpool.Put(sb)\n\t\treturn err\n\t}\n\n\t_, err = s.w.Write(sb.Bytes())\n\ts.cur = 0\n\tbytebufferpool.Put(sb)\n\treturn err\n}", "func flush(logger *zap.Logger) {\n\t_ = logger.Sync()\n\teventingmetrics.FlushExporter()\n}", "func (p *Pools) Flush(force bool) {\n\tvar wgFlush sync.WaitGroup\n\tvar tcpFlushed int64\n\tvar tcpCount int64\n\tvar udpFlushed int64\n\tvar udpCount int64\n\tvar counterLock sync.Mutex\n\tfor _, pool := range p.pools {\n\t\tpool.flush(force, &wgFlush, &tcpFlushed, &tcpCount, &udpFlushed, &udpCount, &counterLock)\n\t}\n\twgFlush.Wait()\n\tfmt.Println(humanize.Comma(tcpFlushed), \"\\t/\", humanize.Comma(tcpCount), \"TCP Flows flushed\")\n\tfmt.Println(humanize.Comma(udpFlushed), \"\\t/\", humanize.Comma(udpCount), \"UDP Flows flushed\")\n\twgFlush.Wait()\n}", "func (etcd *EtcdSource) Flush() (err error) {\n\tif etcd.writeChan != nil {\n\t\tclose(etcd.writeChan)\n\t}\n\n\t// wait for flush to complete\n\tfor err = range etcd.flushChan {\n\t\tlog.Printf(\"config:EtcdSource %v: Flush: %v\", etcd, err)\n\t}\n\n\treturn\n}", "func flushAll() {\n\tclients.Range(func(h *ClientHandler) {\n\t\th.Flush()\n\t})\n}", "func (f *AggregationFlusher) Flush(ctx context.Context) error {\n\treturn f.Sink.Aggregate(ctx, f.Source.FlushMetrics())\n}", "func (l *Logger) Flush() {\n\tfor _, l := range l.outputs {\n\t\tl.Flush()\n\t}\n}", "func (r *promReporter) Flush() {\n\n}", "func (s *StatsdClient) Flush() error {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\n\ts.counts = make(map[string]int64)\n\treturn nil\n}", "func (b *RecordBuffer) Flush() {\n\tb.recordsInBuffer = b.recordsInBuffer[:0]\n\tb.sequencesInBuffer = b.sequencesInBuffer[:0]\n}", "func (a *MetricAggregator) Flush(flushInterval time.Duration) {\n\ta.statser.Gauge(\"aggregator.metricmaps_received\", float64(a.metricMapsReceived), nil)\n\n\tflushInSeconds := float64(flushInterval) / float64(time.Second)\n\n\ta.metricMap.Counters.Each(func(key, tagsKey string, counter gostatsd.Counter) {\n\t\tcounter.PerSecond = float64(counter.Value) / flushInSeconds\n\t\ta.metricMap.Counters[key][tagsKey] = counter\n\t})\n\n\ta.metricMap.Timers.Each(func(key, tagsKey string, timer gostatsd.Timer) {\n\t\tif hasHistogramTag(timer) {\n\t\t\ttimer.Histogram = latencyHistogram(timer, a.histogramLimit)\n\t\t\ta.metricMap.Timers[key][tagsKey] = timer\n\t\t\treturn\n\t\t}\n\n\t\tif count := len(timer.Values); count > 0 {\n\t\t\tsort.Float64s(timer.Values)\n\t\t\ttimer.Min = timer.Values[0]\n\t\t\ttimer.Max = timer.Values[count-1]\n\t\t\tn := len(timer.Values)\n\t\t\tcount := float64(n)\n\n\t\t\tcumulativeValues := make([]float64, n)\n\t\t\tcumulSumSquaresValues := make([]float64, n)\n\t\t\tcumulativeValues[0] = timer.Min\n\t\t\tcumulSumSquaresValues[0] = timer.Min * timer.Min\n\t\t\tfor i := 1; i < n; i++ {\n\t\t\t\tcumulativeValues[i] = timer.Values[i] + cumulativeValues[i-1]\n\t\t\t\tcumulSumSquaresValues[i] = timer.Values[i]*timer.Values[i] + cumulSumSquaresValues[i-1]\n\t\t\t}\n\n\t\t\tvar sumSquares = timer.Min * timer.Min\n\t\t\tvar mean = timer.Min\n\t\t\tvar sum = timer.Min\n\t\t\tvar thresholdBoundary = timer.Max\n\n\t\t\tfor pct, pctStruct := range a.percentThresholds {\n\t\t\t\tnumInThreshold := n\n\t\t\t\tif n > 1 {\n\t\t\t\t\tnumInThreshold = int(round(math.Abs(pct) / 100 * count))\n\t\t\t\t\tif numInThreshold == 0 {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif pct > 0 {\n\t\t\t\t\t\tthresholdBoundary = timer.Values[numInThreshold-1]\n\t\t\t\t\t\tsum = cumulativeValues[numInThreshold-1]\n\t\t\t\t\t\tsumSquares = cumulSumSquaresValues[numInThreshold-1]\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthresholdBoundary = timer.Values[n-numInThreshold]\n\t\t\t\t\t\tsum = cumulativeValues[n-1] - cumulativeValues[n-numInThreshold-1]\n\t\t\t\t\t\tsumSquares = cumulSumSquaresValues[n-1] - cumulSumSquaresValues[n-numInThreshold-1]\n\t\t\t\t\t}\n\t\t\t\t\tmean = sum / float64(numInThreshold)\n\t\t\t\t}\n\n\t\t\t\tif !a.disabledSubtypes.CountPct {\n\t\t\t\t\ttimer.Percentiles.Set(pctStruct.count, float64(numInThreshold))\n\t\t\t\t}\n\t\t\t\tif !a.disabledSubtypes.MeanPct {\n\t\t\t\t\ttimer.Percentiles.Set(pctStruct.mean, mean)\n\t\t\t\t}\n\t\t\t\tif !a.disabledSubtypes.SumPct {\n\t\t\t\t\ttimer.Percentiles.Set(pctStruct.sum, sum)\n\t\t\t\t}\n\t\t\t\tif !a.disabledSubtypes.SumSquaresPct {\n\t\t\t\t\ttimer.Percentiles.Set(pctStruct.sumSquares, sumSquares)\n\t\t\t\t}\n\t\t\t\tif pct > 0 {\n\t\t\t\t\tif !a.disabledSubtypes.UpperPct {\n\t\t\t\t\t\ttimer.Percentiles.Set(pctStruct.upper, thresholdBoundary)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif !a.disabledSubtypes.LowerPct {\n\t\t\t\t\t\ttimer.Percentiles.Set(pctStruct.lower, thresholdBoundary)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tsum = cumulativeValues[n-1]\n\t\t\tsumSquares = cumulSumSquaresValues[n-1]\n\t\t\tmean = sum / count\n\n\t\t\tvar sumOfDiffs float64\n\t\t\tfor i := 0; i < n; i++ {\n\t\t\t\tsumOfDiffs += (timer.Values[i] - mean) * (timer.Values[i] - mean)\n\t\t\t}\n\n\t\t\tmid := int(math.Floor(count / 2))\n\t\t\tif math.Mod(count, 2) == 0 {\n\t\t\t\ttimer.Median = (timer.Values[mid-1] + timer.Values[mid]) / 2\n\t\t\t} else {\n\t\t\t\ttimer.Median = timer.Values[mid]\n\t\t\t}\n\n\t\t\ttimer.Mean = mean\n\t\t\ttimer.StdDev = math.Sqrt(sumOfDiffs / count)\n\t\t\ttimer.Sum = sum\n\t\t\ttimer.SumSquares = sumSquares\n\n\t\t\ttimer.Count = int(round(timer.SampledCount))\n\t\t\ttimer.PerSecond = timer.SampledCount / flushInSeconds\n\t\t} else {\n\t\t\ttimer.Count = 0\n\t\t\ttimer.SampledCount = 0\n\t\t\ttimer.PerSecond = 0\n\t\t}\n\t\ta.metricMap.Timers[key][tagsKey] = timer\n\t})\n}", "func (evc *EventCache) Flush() {\n\tfor _, ei := range evc.events {\n\t\tevc.evsw.FireEvent(ei.event, ei.data)\n\t}\n\tevc.events = make([]eventInfo, eventsBufferSize)\n}", "func (m *Metric) Done() {\n\t// End open spans.\n\tm.mu.Lock() // Lock protects the slice of spans changing size.\n\tvar zeroTime time.Time\n\tfor _, s := range m.spans {\n\t\tif s.EndTime == zeroTime {\n\t\t\ts.End()\n\t\t}\n\t}\n\tm.mu.Unlock()\n\n\tif atomic.LoadInt32(&registered) == 0 {\n\t\t// No saver registered,\n\t\t// don't send any metrics.\n\t\treturn\n\t}\n\n\tselect {\n\tcase saveQueue <- m:\n\t\t// Sent\n\tdefault:\n\t\t// Warn if channel is full.\n\t\tlog.Error.Printf(\"metric: channel is full. Dropping metric %q.\", m.Name)\n\t}\n}", "func (s *Layer) Flush() {\n\ts.Pool = Pool{}\n}", "func FlushSend(q Queue) {\n\tif flusher, ok := q.(Flusher); ok {\n\t\tflusher.FlushSend()\n\t}\n}", "func (ingest *Ingestion) Flush() error {\n\terr := ingest.commit()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn ingest.Start()\n}", "func Flush() {\n\tsentry.Flush(3 * time.Second)\n}", "func (s *Collector) FlushAlways(interval time.Duration, errs chan<- error) {\n\tfor range time.Tick(interval) {\n\t\terrs <- s.Flush()\n\t}\n}", "func (c *QueuedChan) flush() {\n\t// Flush queue.\n\tfor elem := c.Front(); nil != elem; elem = c.Front() {\n\t\tc.popc <- elem.Value\n\t\tc.List.Remove(elem)\n\t}\n}", "func (ab *AutoflushBuffer) Flush(ctx context.Context) {\n\tab.Lock()\n\tdefer ab.Unlock()\n\tab.flushUnsafe(ctx, ab.Contents.Drain())\n}", "func (dam *dam) flush(err error) {\n\tclose(dam.barrier)\n\n\t// Reset barrier\n\tdam.lock.Lock()\n\tdam.barrier = make(chan error)\n\tdam.lock.Unlock()\n}", "func (mlog *MultiLogger) Flush() {\n\tmlog.Lock()\n\tdefer mlog.Unlock()\n\n\tif mlog.isClosed {\n\t\treturn\n\t}\n\tmlog.qerr <- cmdFlush\n\tmlog.qout <- cmdFlush\n\t<-mlog.flushq\n\t<-mlog.flushq\n}", "func (iter *Iterator) Flush() error { return iter.impl.Flush() }", "func (c *Conn) Flush() error {\n\tif c.FlushMock != nil {\n\t\treturn c.FlushMock()\n\t}\n\n\tif len(c.queue) > 0 {\n\t\tfor _, cmd := range c.queue {\n\t\t\treply, err := c.do(cmd.commandName, cmd.args...)\n\t\t\tc.replies = append(c.replies, replyElement{reply: reply, err: err})\n\t\t}\n\t\tc.queue = []queueElement{}\n\t}\n\n\treturn nil\n}", "func (h *heapSorter) flush(ctx context.Context, maxResolvedTs uint64) error {\n\tcaptureAddr := util.CaptureAddrFromCtx(ctx)\n\tchangefeedID := util.ChangefeedIDFromCtx(ctx)\n\t_, tableName := util.TableIDFromCtx(ctx)\n\tsorterFlushCountHistogram.WithLabelValues(captureAddr, changefeedID, tableName).Observe(float64(h.heap.Len()))\n\n\tisEmptyFlush := h.heap.Len() == 0\n\tif isEmptyFlush {\n\t\treturn nil\n\t}\n\tvar (\n\t\tbackEnd backEnd\n\t\tlowerBound uint64\n\t)\n\n\tif !isEmptyFlush {\n\t\tvar err error\n\t\tbackEnd, err = pool.alloc(ctx)\n\t\tif err != nil {\n\t\t\treturn errors.Trace(err)\n\t\t}\n\n\t\tlowerBound = h.heap[0].entry.CRTs\n\t}\n\n\ttask := &flushTask{\n\t\ttaskID: h.taskCounter,\n\t\theapSorterID: h.id,\n\t\tbackend: backEnd,\n\t\ttsLowerBound: lowerBound,\n\t\tmaxResolvedTs: maxResolvedTs,\n\t\tfinished: make(chan error, 2),\n\t}\n\th.taskCounter++\n\n\tvar oldHeap sortHeap\n\tif !isEmptyFlush {\n\t\ttask.dealloc = func() error {\n\t\t\tif task.backend != nil {\n\t\t\t\ttask.backend = nil\n\t\t\t\treturn pool.dealloc(backEnd)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t\toldHeap = h.heap\n\t\th.heap = make(sortHeap, 0, 65536)\n\t} else {\n\t\ttask.dealloc = func() error {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tlog.Debug(\"Unified Sorter new flushTask\",\n\t\tzap.String(\"table\", tableNameFromCtx(ctx)),\n\t\tzap.Int(\"heap-id\", task.heapSorterID),\n\t\tzap.Uint64(\"resolvedTs\", task.maxResolvedTs))\n\n\tgo func() {\n\t\tif isEmptyFlush {\n\t\t\treturn\n\t\t}\n\t\tbackEndFinal := backEnd\n\t\twriter, err := backEnd.writer()\n\t\tif err != nil {\n\t\t\tif backEndFinal != nil {\n\t\t\t\t_ = task.dealloc()\n\t\t\t}\n\t\t\ttask.finished <- errors.Trace(err)\n\t\t\treturn\n\t\t}\n\n\t\tdefer func() {\n\t\t\t// handle errors (or aborts) gracefully to prevent resource leaking (especially FD's)\n\t\t\tif writer != nil {\n\t\t\t\t_ = writer.flushAndClose()\n\t\t\t}\n\t\t\tif backEndFinal != nil {\n\t\t\t\t_ = task.dealloc()\n\t\t\t}\n\t\t\tclose(task.finished)\n\t\t}()\n\n\t\tfor oldHeap.Len() > 0 {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\ttask.finished <- ctx.Err()\n\t\t\tdefault:\n\t\t\t}\n\n\t\t\tevent := heap.Pop(&oldHeap).(*sortItem).entry\n\t\t\terr := writer.writeNext(event)\n\t\t\tif err != nil {\n\t\t\t\ttask.finished <- errors.Trace(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tdataSize := writer.dataSize()\n\t\tatomic.StoreInt64(&task.dataSize, int64(dataSize))\n\t\teventCount := writer.writtenCount()\n\n\t\twriter1 := writer\n\t\twriter = nil\n\t\terr = writer1.flushAndClose()\n\t\tif err != nil {\n\t\t\ttask.finished <- errors.Trace(err)\n\t\t\treturn\n\t\t}\n\n\t\tbackEndFinal = nil\n\t\ttask.finished <- nil // DO NOT access `task` beyond this point in this function\n\t\tlog.Debug(\"Unified Sorter flushTask finished\",\n\t\t\tzap.Int(\"heap-id\", task.heapSorterID),\n\t\t\tzap.String(\"table\", tableNameFromCtx(ctx)),\n\t\t\tzap.Uint64(\"resolvedTs\", task.maxResolvedTs),\n\t\t\tzap.Uint64(\"data-size\", dataSize),\n\t\t\tzap.Int(\"size\", eventCount))\n\t}()\n\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tcase h.outputCh <- task:\n\t}\n\treturn nil\n}", "func (m *Migrator) Flush() error {\n\tvar wg sync.WaitGroup\n\tvar mu sync.Mutex\n\tvar errs HostErrorSet\n\tfor hostKey, s := range m.shards {\n\t\tif s.Len() == 0 {\n\t\t\tcontinue\n\t\t}\n\t\twg.Add(1)\n\t\tgo func(hostKey hostdb.HostPublicKey, s *renter.SectorBuilder) {\n\t\t\tdefer wg.Done()\n\t\t\th, err := m.hosts.acquire(hostKey)\n\t\t\tif err != nil {\n\t\t\t\tmu.Lock()\n\t\t\t\terrs = append(errs, &HostError{hostKey, err})\n\t\t\t\tmu.Unlock()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tsector := s.Finish()\n\t\t\troot, err := h.Append(sector)\n\t\t\tm.hosts.release(hostKey)\n\t\t\tif err != nil {\n\t\t\t\tmu.Lock()\n\t\t\t\terrs = append(errs, &HostError{hostKey, err})\n\t\t\t\tmu.Unlock()\n\t\t\t\treturn\n\t\t\t}\n\t\t\ts.SetMerkleRoot(root)\n\t\t}(hostKey, s)\n\t}\n\twg.Wait()\n\tif len(errs) > 0 {\n\t\treturn errs\n\t}\n\n\tfor _, fn := range m.onFlush {\n\t\tif err := fn(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tm.onFlush = m.onFlush[:0]\n\n\tfor _, s := range m.shards {\n\t\ts.Reset()\n\t}\n\n\treturn nil\n}", "func (client *LDClient) Flush() {\n\tclient.eventProcessor.Flush()\n}", "func (t Tracker) FlushEmitter() {\n\tt.Emitter.Flush()\n}", "func (honest *Honest) flushUpdates() {\n\n\thonest.blockUpdates = honest.blockUpdates[:0]\n}", "func (r *Transformer) flushUncombined(ctx context.Context) {\n\tfor source := range r.batchMap {\n\t\tfor _, entry := range r.batchMap[source].entries {\n\t\t\tr.Write(ctx, entry)\n\t\t}\n\t\tr.removeBatch(source)\n\t}\n\tr.ticker.Reset(r.forceFlushTimeout)\n}", "func (cl *Client) Flush(ctx context.Context) error {\n\tp := &cl.producer\n\n\t// Signal to finishRecord that we want to be notified once buffered hits 0.\n\t// Also forbid any new producing to start a linger.\n\tatomic.AddInt32(&p.flushing, 1)\n\tdefer atomic.AddInt32(&p.flushing, -1)\n\n\tcl.cfg.logger.Log(LogLevelInfo, \"flushing\")\n\tdefer cl.cfg.logger.Log(LogLevelDebug, \"flushed\")\n\n\t// At this point, if lingering is configured, nothing will _start_ a\n\t// linger because the producer's flushing atomic int32 is nonzero. We\n\t// must wake anything that could be lingering up, after which all sinks\n\t// will loop draining.\n\tif cl.cfg.linger > 0 || cl.cfg.manualFlushing {\n\t\tfor _, parts := range p.topics.load() {\n\t\t\tfor _, part := range parts.load().partitions {\n\t\t\t\tpart.records.unlingerAndManuallyDrain()\n\t\t\t}\n\t\t}\n\t}\n\n\tquit := false\n\tdone := make(chan struct{})\n\tgo func() {\n\t\tp.notifyMu.Lock()\n\t\tdefer p.notifyMu.Unlock()\n\t\tdefer close(done)\n\n\t\tfor !quit && atomic.LoadInt64(&p.bufferedRecords) > 0 {\n\t\t\tp.notifyCond.Wait()\n\t\t}\n\t}()\n\n\tselect {\n\tcase <-done:\n\t\treturn nil\n\tcase <-ctx.Done():\n\t\tp.notifyMu.Lock()\n\t\tquit = true\n\t\tp.notifyMu.Unlock()\n\t\tp.notifyCond.Broadcast()\n\t\treturn ctx.Err()\n\t}\n}", "func (w *ServiceWriter) Flush() {\n\tif !w.updated {\n\t\treturn\n\t}\n\tw.updated = false\n\n\tserviceBuffer := w.serviceBuffer\n\n\tlog.Debugf(\"going to flush updated service metadata, %d services\", len(serviceBuffer))\n\tatomic.StoreInt64(&w.stats.Services, int64(len(serviceBuffer)))\n\n\tdata, err := model.EncodeServicesPayload(serviceBuffer)\n\tif err != nil {\n\t\tlog.Errorf(\"encoding issue: %v\", err)\n\t\treturn\n\t}\n\n\theaders := map[string]string{\n\t\tlanguageHeaderKey: strings.Join(info.Languages(), \"|\"),\n\t\t\"Content-Type\": \"application/json\",\n\t}\n\n\tatomic.AddInt64(&w.stats.Bytes, int64(len(data)))\n\n\tstartFlush := time.Now()\n\n\t// Send the payload to the endpoint\n\terr = w.endpoint.Write(data, headers)\n\n\tflushTime := time.Since(startFlush)\n\n\t// TODO: if error, depending on why, replay later.\n\tif err != nil {\n\t\tatomic.AddInt64(&w.stats.Errors, 1)\n\t\tlog.Errorf(\"failed to flush service payload, time:%s, size:%d bytes, error: %s\", flushTime, len(data), err)\n\t\treturn\n\t}\n\n\tlog.Infof(\"flushed service payload to the API, time:%s, size:%d bytes\", flushTime, len(data))\n\tstatsd.Client.Gauge(\"datadog.trace_agent.service_writer.flush_duration\", flushTime.Seconds(), nil, 1)\n\tatomic.AddInt64(&w.stats.Payloads, 1)\n}", "func (u *LDSUnit) Flush() {\n\tu.toRead = nil\n\tu.toExec = nil\n\tu.toWrite = nil\n}", "func (r *limitedRowWriter) Flush() {\n\tif r == nil {\n\t\treturn\n\t}\n\n\t// If at least some rows were sent, and no values are pending, then don't\n\t// emit anything, since at least 1 row was previously emitted. This ensures\n\t// that if no rows were ever sent, at least 1 will be emitted, even an empty row.\n\tif r.totalSent != 0 && len(r.currValues) == 0 {\n\t\treturn\n\t}\n\n\tif r.limit > 0 && len(r.currValues) > r.limit {\n\t\tr.currValues = r.currValues[:r.limit]\n\t}\n\tr.c <- r.processValues(r.currValues)\n\tr.currValues = nil\n}", "func (s *State) Flush() {\n\ts.decidedBlocks.Flush()\n\ts.missingBlocks.Flush()\n\ts.unverifiedBlocks.Flush()\n}", "func (s *State) doFlush(c context.Context, state *tsmon.State, settings *tsmonSettings) error {\n\tvar mon monitor.Monitor\n\n\tif s.testingMonitor != nil {\n\t\tmon = s.testingMonitor\n\t} else if info.Get(c).IsDevAppServer() || settings.PubsubProject == \"\" || settings.PubsubTopic == \"\" {\n\t\tmon = monitor.NewDebugMonitor(\"\")\n\t} else {\n\t\ttopic := gcps.NewTopic(settings.PubsubProject, settings.PubsubTopic)\n\t\tlogging.Infof(c, \"Sending metrics to %s\", topic)\n\n\t\t// Create an HTTP client with the default appengine service account. The\n\t\t// client is bound to the context and inherits its deadline.\n\t\tauth, err := gaeauth.Authenticator(c, gcps.PublisherScopes, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tclient, err := auth.Client()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tmon, err = monitor.NewPubsubMonitor(c, client, topic)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := state.Flush(c, mon); err != nil {\n\t\treturn err\n\t}\n\n\tstate.ResetGlobalCallbackMetrics(c)\n\treturn nil\n}", "func (m *mergeWithTimestampsType) Flush() {\n\ttsLen := len(m.timestamps)\n\tif !m.lastRecordSet {\n\t\treturn\n\t}\n\tfor m.timestampIdx < tsLen {\n\t\tm.lastRecord.TimeStamp = m.timestamps[m.timestampIdx]\n\t\tif !m.wrapped.Append(&m.lastRecord) {\n\t\t\treturn\n\t\t}\n\t\tm.timestampIdx++\n\t}\n}", "func (r *ResponseStatusRecorder) Flush() {\n\tif r.flusher != nil {\n\t\tr.flusher.Flush()\n\t}\n}", "func (s *shard) Flush() (err error) {\n\t// another flush process is running\n\tif !s.isFlushing.CAS(false, true) {\n\t\treturn nil\n\t}\n\t// 1. mark flush job doing\n\ts.flushCondition.Add(1)\n\n\tdefer func() {\n\t\t//TODO add commit kv meta after ack successfully\n\t\t// mark flush job complete, notify\n\t\ts.flushCondition.Done()\n\t\ts.isFlushing.Store(false)\n\t}()\n\n\tstartTime := time.Now()\n\t//FIXME stone1100\n\t// index flush\n\tif s.indexDB != nil {\n\t\tif err = s.indexDB.Flush(); err != nil {\n\t\t\ts.logger.Error(\"failed to flush indexDB \",\n\t\t\t\tlogger.Any(\"shardID\", s.id),\n\t\t\t\tlogger.String(\"database\", s.databaseName),\n\t\t\t\tlogger.Error(err))\n\t\t\treturn err\n\t\t}\n\t\ts.logger.Info(\"flush indexDB successfully\",\n\t\t\tlogger.Any(\"shardID\", s.id),\n\t\t\tlogger.String(\"database\", s.databaseName),\n\t\t)\n\t\ts.statistics.indexFlushTimer.UpdateSince(startTime)\n\t}\n\n\tvar waitingFlushMemDB memdb.MemoryDatabase\n\timmutable := s.families.ImmutableEntries()\n\t// flush first immutable memdb\n\tif len(immutable) > 0 {\n\t\twaitingFlushMemDB = immutable[0].memDB\n\t} else {\n\t\ts.mutex.Lock()\n\t\t// force picks a mutable memdb from memory\n\t\tif evictedMutable := s.families.SetLargestMutableMemDBImmutable(); evictedMutable {\n\t\t\twaitingFlushMemDB = s.families.ImmutableEntries()[0].memDB\n\t\t\ts.logger.Info(\"forcefully switch a memdb to immutable for flushing\",\n\t\t\t\tlogger.Any(\"shardID\", s.id),\n\t\t\t\tlogger.String(\"database\", s.databaseName),\n\t\t\t\tlogger.Int64(\"familyTime\", waitingFlushMemDB.FamilyTime()),\n\t\t\t\tlogger.Int64(\"memDBSize\", waitingFlushMemDB.MemSize()),\n\t\t\t)\n\t\t}\n\t\ts.mutex.Unlock()\n\t}\n\tif waitingFlushMemDB == nil {\n\t\ts.logger.Warn(\"there is no memdb to flush\", logger.Any(\"shardID\", s.id))\n\t\treturn nil\n\t}\n\n\tstartTime = time.Now()\n\tif err := s.flushMemoryDatabase(waitingFlushMemDB); err != nil {\n\t\ts.logger.Error(\"failed to flush memdb\",\n\t\t\tlogger.Any(\"shardID\", s.id),\n\t\t\tlogger.String(\"database\", s.databaseName),\n\t\t\tlogger.Int64(\"familyTime\", waitingFlushMemDB.FamilyTime()),\n\t\t\tlogger.Int64(\"memDBSize\", waitingFlushMemDB.MemSize()))\n\t\treturn err\n\t}\n\t// flush success, remove it from the immutable list\n\ts.mutex.Lock()\n\ts.families.RemoveHeadImmutable()\n\ts.mutex.Unlock()\n\n\tendTime := time.Now()\n\ts.logger.Info(\"flush memdb successfully\",\n\t\tlogger.Any(\"shardID\", s.id),\n\t\tlogger.String(\"database\", s.databaseName),\n\t\tlogger.String(\"flush-duration\", endTime.Sub(startTime).String()),\n\t\tlogger.Int64(\"familyTime\", waitingFlushMemDB.FamilyTime()),\n\t\tlogger.Int64(\"memDBSize\", waitingFlushMemDB.MemSize()))\n\ts.statistics.memFlushTimer.UpdateDuration(endTime.Sub(startTime))\n\n\t//FIXME(stone1100) commit replica sequence\n\ts.ackReplicaSeq()\n\treturn nil\n}", "func TestSpanModifyWhileFlushing(t *testing.T) {\n\ttracer, _ := getTestTracer()\n\tdefer tracer.Stop()\n\n\tdone := make(chan struct{})\n\tgo func() {\n\t\tspan := tracer.NewRootSpan(\"pylons.request\", \"pylons\", \"/\")\n\t\tspan.Finish()\n\t\t// It doesn't make much sense to update the span after it's been finished,\n\t\t// but an error in a user's code could lead to this.\n\t\tspan.SetMeta(\"race_test\", \"true\")\n\t\tspan.SetMetric(\"race_test2\", 133.7)\n\t\tspan.SetMetrics(\"race_test3\", 133.7)\n\t\tspan.SetError(errors.New(\"t\"))\n\t\tdone <- struct{}{}\n\t}()\n\n\trun := true\n\tfor run {\n\t\tselect {\n\t\tcase <-done:\n\t\t\trun = false\n\t\tdefault:\n\t\t\ttracer.flushTraces()\n\t\t}\n\t}\n}", "func (res *ServerHTTPResponse) flush(ctx context.Context) {\n\tif res.flushed {\n\t\t/* coverage ignore next line */\n\t\tres.contextLogger.Error(ctx,\n\t\t\t\"Flushed a server response multiple times\",\n\t\t\tzap.String(\"path\", res.Request.URL.Path),\n\t\t)\n\t\t/* coverage ignore next line */\n\t\treturn\n\t}\n\n\tres.flushed = true\n\tres.writeHeader(res.pendingStatusCode)\n\tif _, noContent := noContentStatusCodes[res.pendingStatusCode]; !noContent {\n\t\tres.writeBytes(res.pendingBodyBytes)\n\t}\n\tres.finish(ctx)\n}", "func (n *NodeDrainer) flush(state *state.StateStore) {\n\t// Cancel anything that may be running.\n\tif n.exitFn != nil {\n\t\tn.exitFn()\n\t}\n\n\t// Store the new state\n\tif state != nil {\n\t\tn.state = state\n\t}\n\n\tn.ctx, n.exitFn = context.WithCancel(context.Background())\n\tn.jobWatcher = n.jobFactory(n.ctx, n.queryLimiter, n.state, n.logger)\n\tn.nodeWatcher = n.nodeFactory(n.ctx, n.queryLimiter, n.state, n.logger, n)\n\tn.deadlineNotifier = n.deadlineNotifierFactory(n.ctx)\n\tn.nodes = make(map[string]*drainingNode, 32)\n}", "func (n *Network) Flush() {\n\t// Flush back recursively\n\tfor _, node := range n.all_nodes {\n\t\tnode.Flushback()\n\t}\n}", "func (s *syncSchedule) flush() error {\n\tfor a := range s.txs {\n\t\tif err := a.writeTxStore(s.dir); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdelete(s.txs, a)\n\t}\n\n\tfor a := range s.wallets {\n\t\tif err := a.writeWallet(s.dir); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdelete(s.wallets, a)\n\t}\n\n\treturn nil\n}", "func (s *server) ServerlessFlush() {\n\ts.log.Debug(\"Received a Flush trigger\")\n\n\t// make all workers flush their aggregated data (in the batchers) into the time samplers\n\ts.serverlessFlushChan <- true\n\n\tstart := time.Now()\n\t// flush the aggregator to have the serializer/forwarder send data to the backend.\n\t// We add 10 seconds to the interval to ensure that we're getting the whole sketches bucket\n\ts.demultiplexer.ForceFlushToSerializer(start.Add(time.Second*10), true)\n}", "func (set *Set) Flush() error {\n\t_, err := set.Parent.run(\"flush\", set.Name)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (ab *Buffer) Dispatch() {\n\tab.Latch.Started()\n\n\tvar stopping <-chan struct{}\n\tvar flushWorker *async.Worker\n\tvar flush Flush\n\tfor {\n\t\tstopping = ab.Latch.NotifyStopping()\n\t\tselect {\n\t\tcase <-stopping:\n\t\t\tab.Latch.Stopped()\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\t\tselect {\n\t\tcase flush = <-ab.flushes:\n\t\t\tselect {\n\t\t\tcase flushWorker = <-ab.flushWorkersReady:\n\t\t\t\tflushWorker.Work <- flush\n\t\t\tcase <-stopping:\n\t\t\t\tab.flushes <- flush\n\t\t\t\tab.Latch.Stopped()\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-stopping:\n\t\t\tab.Latch.Stopped()\n\t\t\treturn\n\t\t}\n\t}\n}", "func (a *Async) flushBuf(b *buffer) {\n\ttasks := b.Tasks()\n\tif len(tasks) > 0 {\n\t\tfor _, t := range tasks {\n\t\t\ta.wait.Add(1)\n\t\t\tgo func(t *task) {\n\t\t\t\tt.Do()\n\t\t\t\ta.wait.Done()\n\t\t\t}(t)\n\t\t}\n\t\ta.wait.Wait()\n\t\tb.Reset()\n\t}\n}", "func (lp *LogFile) Flush() {\n\tcomplete := make(chan bool)\n\tlp.messages <- logMessage{action: flushLog, complete: complete}\n\t<-complete\n}", "func Flush(flusher Flusher, swallow bool) (err error) {\n\tif err = flusher.Flush(); err == nil || !swallow {\n\t\treturn err\n\t}\n\tlog.Println(\"error thrown while flushing Flusher.\", err)\n\treturn nil\n}", "func FlushAt(e *events.Event, db Storer, tm time.Time) error {\n\ts := getSnapshot()\n\tdefer putSnapshot(s)\n\ts.Counters = e.Flush(s.Counters[:0])\n\tif len(s.Counters) == 0 {\n\t\treturn nil\n\t}\n\ts.Labels, s.Time = e.Labels, tm\n\tif err := db.Store(s); err != nil {\n\t\te.Merge(s.Counters)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (_e *MockDataCoord_Expecter) Flush(ctx interface{}, req interface{}) *MockDataCoord_Flush_Call {\n\treturn &MockDataCoord_Flush_Call{Call: _e.mock.On(\"Flush\", ctx, req)}\n}" ]
[ "0.7013252", "0.70100605", "0.68950844", "0.67272437", "0.67241", "0.6619081", "0.65922195", "0.6541169", "0.6531564", "0.64752495", "0.6468364", "0.64626235", "0.6339146", "0.6326567", "0.63122135", "0.63055515", "0.62817365", "0.6278763", "0.6242171", "0.6241586", "0.6190081", "0.61752135", "0.61687803", "0.61512285", "0.6143801", "0.6119428", "0.60714424", "0.60347396", "0.60287213", "0.60254604", "0.60249454", "0.6012976", "0.6012053", "0.6001679", "0.6000438", "0.5981777", "0.5967903", "0.5961433", "0.5959291", "0.5941297", "0.5935195", "0.59328926", "0.593208", "0.5906569", "0.59040296", "0.5901941", "0.58971757", "0.5897103", "0.58864933", "0.58799464", "0.5877384", "0.5871558", "0.58678216", "0.5863703", "0.5860835", "0.5859839", "0.58462775", "0.58090776", "0.5805481", "0.57963324", "0.57853603", "0.57850564", "0.5774589", "0.5769437", "0.57494414", "0.57479626", "0.5727507", "0.57236", "0.57180387", "0.57180196", "0.571281", "0.57108927", "0.57024825", "0.5699587", "0.56948125", "0.56776094", "0.56758195", "0.5674449", "0.5665765", "0.56628597", "0.5662371", "0.5657985", "0.5653671", "0.5649608", "0.5637568", "0.56304437", "0.562761", "0.56056166", "0.558836", "0.55842924", "0.5573376", "0.5559899", "0.555125", "0.5541693", "0.55353844", "0.55349815", "0.55190766", "0.5502075", "0.54996467", "0.5496893" ]
0.7357907
0
NewRemoteCollector creates a collector that sends data to a collector server (created with NewServer). It sends data immediately when Collect is called. To send data in chunks, use a ChunkedCollector.
NewRemoteCollector создает сборщик, отправляющий данные на сервер сборщика (созданный с помощью NewServer). Он сразу отправляет данные при вызове Collect. Чтобы отправлять данные порциями, используйте ChunkedCollector.
func NewRemoteCollector(addr string) *RemoteCollector { return &RemoteCollector{ addr: addr, dial: func() (net.Conn, error) { return net.Dial("tcp", addr) }, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewRemoteAmboyStatsCollector(env cedar.Environment, id string) amboy.Job {\n\tj := makeAmboyStatsCollector()\n\tj.ExcludeLocal = true\n\tj.env = env\n\tj.SetID(fmt.Sprintf(\"%s-%s\", amboyStatsCollectorJobName, id))\n\treturn j\n}", "func NewCollector() *Collector {\n\tcollector := &Collector{\n\t\tresults: make(chan interface{}, 100),\n\t\tdone: make(chan interface{}),\n\t}\n\tgo collector.process()\n\treturn collector\n}", "func NewCollector(config *CollectorConfig) (Collector, error) {\n\tc := &standardCollector{\n\t\trunning: true,\n\t\tevents: make(chan Event, config.EventBufferSize),\n\t\tconfig: config,\n\t\tneighbors: make(map[string]neighbor),\n\t\tRWMutex: &sync.RWMutex{},\n\t}\n\n\treturn c, nil\n}", "func NewCollector(period time.Duration, collectFunc func() []Measurement) *Collector {\n\tcollector := &Collector{\n\t\tperiod: period,\n\t\tcollectFunc: collectFunc,\n\t\tlastSendingDate: -1,\n\t}\n\n\tif sources == nil {\n\t\tsources = make([]DataSource, 0)\n\t\tgo sendingLoop()\n\t}\n\n\tif UseGlobalEngine {\n\t\tcollector.Engine = Engine\n\t} else {\n\t\tcollector.Engine = &req.Engine{}\n\t}\n\n\tsources = append(sources, collector)\n\n\treturn collector\n}", "func NewCollector() collector.RPCCollector {\n\treturn &interfaceCollector{}\n}", "func NewCollector(store *store.MemoryStore) *Collector {\n\treturn &Collector{\n\t\tstore: store,\n\t\tstopChan: make(chan struct{}),\n\t\tdoneChan: make(chan struct{}),\n\t}\n}", "func NewCollector() Collector {\n\treturn Collector{client: NewClient(time.Second * 5)}\n}", "func NewTLSRemoteCollector(addr string, tlsConfig *tls.Config) *RemoteCollector {\n\treturn &RemoteCollector{\n\t\taddr: addr,\n\t\tdial: func() (net.Conn, error) {\n\t\t\treturn tls.Dial(\"tcp\", addr, tlsConfig)\n\t\t},\n\t}\n}", "func NewCollector() collector.RPCCollector {\n\treturn &vpwsCollector{}\n}", "func NewCollector(username string, token string, source string, timeout time.Duration, waitGroup *sync.WaitGroup) Collector {\n\treturn &collector{\n\t\turl: metricsEndpont,\n\t\tusername: username,\n\t\ttoken: token,\n\t\tsource: source,\n\t\ttimeout: timeout,\n\n\t\thttpClient: &http.Client{\n\t\t\tTimeout: time.Second * 30,\n\t\t},\n\t\twaitGroup: waitGroup,\n\t\tstop: make(chan bool),\n\t\tbuffer: make(chan gauge, 10000),\n\t}\n}", "func NewCollector() *Collector {\n\twg := &sync.WaitGroup{}\n\tevtCh := make(chan *eventsapi.ClientEvent, collChanBufferSize)\n\n\tc := &Collector{&atomic.Value{}, wg, evtCh}\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\n\t\tvar events []*eventsapi.ClientEvent\n\t\tfor evt := range evtCh {\n\t\t\tevents = append(events, evt)\n\t\t}\n\n\t\tc.val.Store(events)\n\t}()\n\n\treturn c\n}", "func NewCollector(client *api.Client, collectSnaphots, collectNetwork bool) prometheus.Collector {\n\treturn &VMCollector{client: client, collectSnapshots: collectSnaphots, collectNetwork: collectNetwork}\n}", "func NewServer(l net.Listener, c Collector) *CollectorServer {\n\tcs := &CollectorServer{c: c, l: l}\n\treturn cs\n}", "func NewCollector(l *logrus.Entry, updateInterval time.Duration) *Collector {\n\tcol := &Collector{\n\t\tMsgEvtChan: make(chan *discordgo.Message, 1000),\n\t\tinterval: updateInterval,\n\t\tl: l,\n\t\tchannels: make(map[int64]*entry),\n\t}\n\n\tgo col.run()\n\n\treturn col\n}", "func NewCollector() collector.RPCCollector {\n\treturn &storageCollector{}\n}", "func NewCollector() Collector {\n\treturn make(Collector)\n}", "func NewCollector(config *Config) (coll *Collector, err error) {\n\tvar gelfWriter *gelf.Writer\n\n\tif gelfWriter, err = gelf.NewWriter(config.Graylog.Address); err != nil {\n\t\treturn nil, err\n\t}\n\n\tcoll = new(Collector)\n\tcoll.writer = gelfWriter\n\tcoll.host = config.Collector.Hostname\n\n\treturn coll, nil\n}", "func NewCollector(rcClientId string, kubernetesClusterId string) TelemetryCollector {\n\treturn &telemetryCollector{\n\t\tclient: httputils.NewResetClient(httpClientResetInterval, httpClientFactory(httpClientTimeout)),\n\t\thost: utils.GetMainEndpoint(config.Datadog, mainEndpointPrefix, mainEndpointUrlKey),\n\t\tuserAgent: \"Datadog Cluster Agent\",\n\t\trcClientId: rcClientId,\n\t\tkubernetesClusterId: kubernetesClusterId,\n\t}\n}", "func NewCollector(api API) *Collector {\n\treturn &Collector{api: api}\n}", "func NewCollector(cl client.Client) prometheus.Collector {\n\treturn &collector{\n\t\tcl: cl,\n\t}\n}", "func NewCollector(logicalSystem string) collector.RPCCollector {\n\treturn &bgpCollector{LogicalSystem: logicalSystem}\n}", "func New() *Collector { return &Collector{} }", "func NewLocalCollector(s Store) Collector {\n\treturn s\n}", "func NewCollector(\n\tlogger *log.Logger, server lxd.InstanceServer) prometheus.Collector {\n\treturn &collector{logger: logger, server: server}\n}", "func NewRemote(ctx context.Context, conn *grpc.ClientConn) Subjects {\n\treturn &remote{\n\t\tclient: NewServiceClient(conn),\n\t}\n}", "func NewCollector(storageLocation v1.StorageLocation, gitter gits.Gitter, gitKind string) (Collector, error) {\n\tclassifier := storageLocation.Classifier\n\tif classifier == \"\" {\n\t\tclassifier = \"default\"\n\t}\n\tgitURL := storageLocation.GitURL\n\tif gitURL != \"\" {\n\t\treturn NewGitCollector(gitter, gitURL, storageLocation.GetGitBranch(), gitKind)\n\t}\n\tbucketProvider, err := factory.NewBucketProviderFromTeamSettingsConfigurationOrDefault(clients.NewFactory(), storageLocation)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"there was a problem obtaining the bucket provider from cluster configuratio\")\n\t}\n\treturn NewBucketCollector(storageLocation.BucketURL, classifier, bucketProvider)\n}", "func NewCollector() collector.RPCCollector {\n\treturn &environmentCollector{}\n}", "func NewCollector() collector.RPCCollector {\n\treturn &environmentCollector{}\n}", "func NewCollector(brokerURL string, s storage.Storage) *Collector {\n\tbroker, err := NewBroker(brokerURL)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tch, err := broker.Channel()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t_, err = ch.QueueDeclare(\n\t\tspecsQueueName, // name\n\t\ttrue, // durable\n\t\tfalse, // delete when usused\n\t\tfalse, // exclusive\n\t\tfalse, // noWait\n\t\tnil, // arguments\n\t)\n\n\tdc, _ := ch.Consume(\n\t\tspecsQueueName, // queue\n\t\t\"\", // consumer\n\t\ttrue, // auto-ack\n\t\tfalse, // exclusive\n\t\tfalse, // no-local\n\t\tfalse, // no-wait\n\t\tnil, // args\n\t)\n\n\treturn &Collector{broker, ch, dc, s}\n}", "func NewCollector() collector.RPCCollector {\n\treturn &isisCollector{}\n}", "func NewCollector(store *forensicstore.ForensicStore, tempDir string, definitions []goartifacts.ArtifactDefinition) (*LiveCollector, error) {\n\tprovidesMap := map[string][]goartifacts.Source{}\n\n\tdefinitions = goartifacts.FilterOS(definitions)\n\n\tfor _, definition := range definitions {\n\t\tfor _, source := range definition.Sources {\n\t\t\tfor _, provide := range source.Provides {\n\t\t\t\tkey := strings.TrimPrefix(provide.Key, \"environ_\")\n\t\t\t\tif providingSources, ok := providesMap[key]; !ok {\n\t\t\t\t\tprovidesMap[key] = []goartifacts.Source{source}\n\t\t\t\t} else {\n\t\t\t\t\tprovidesMap[key] = append(providingSources, source)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tsourceFS, err := systemfs.New()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"system fs creation failed: %w\", err)\n\t}\n\n\treturn &LiveCollector{\n\t\tSourceFS: sourceFS,\n\t\tregistryfs: registryfs.New(),\n\t\tStore: store,\n\t\tTempDir: tempDir,\n\t\tprovidesMap: providesMap,\n\t\tknowledgeBase: map[string][]string{},\n\t}, nil\n}", "func NewCollector(cfg *config.AgentConfig) TelemetryCollector {\n\tif !cfg.TelemetryConfig.Enabled {\n\t\treturn &noopTelemetryCollector{}\n\t}\n\n\tvar endpoints []config.Endpoint\n\tfor _, endpoint := range cfg.TelemetryConfig.Endpoints {\n\t\tu, err := url.Parse(endpoint.Host)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tu.Path = \"/api/v2/apmtelemetry\"\n\t\tendpointWithPath := *endpoint\n\t\tendpointWithPath.Host = u.String()\n\n\t\tendpoints = append(endpoints, endpointWithPath)\n\t}\n\n\treturn &telemetryCollector{\n\t\tclient: cfg.NewHTTPClient(),\n\t\tendpoints: endpoints,\n\t\tuserAgent: fmt.Sprintf(\"Datadog Trace Agent/%s/%s\", cfg.AgentVersion, cfg.GitCommit),\n\n\t\tcfg: cfg,\n\t\tcollectedStartupError: &atomic.Bool{},\n\t}\n}", "func NewRemote() (Catalog, error) {\n\treturn newRemoteFunc()\n}", "func NewCollector(config CollectorConfig, rawConfig *common.Config) (*Collector, error) {\n\n\t// Compile the configured pattern\n\tpattern, err := regexp.Compile(config.Pattern)\n\tif err != nil {\n\t\tlogp.Warn(\"Unable to parse regular expression: %s\", err)\n\t\treturn nil, err\n\t}\n\n\t// Create our Collector with its channel signals\n\tcollector := Collector{\n\t\tPattern: pattern,\n\t\tconfig: config,\n\n\t\tprospectorDone: make(chan struct{}),\n\t\tlines: make(chan string),\n\t\tDone: make(chan struct{}),\n\t\tStopped: make(chan struct{}),\n\t}\n\n\t// Initialize our ticker for handling timeouts\n\tif config.Timeout.Interval > 0 {\n\t\t// If a timeout is set then create a new ticker and save wrap its channel with a variable\n\t\tcollector.ticker = time.NewTicker(config.Timeout.Interval)\n\t\tcollector.timeoutChannel = collector.ticker.C\n\t} else {\n\t\t// If a timeout is not set then create just a generic channel that will never return.\n\t\t// It just makes generalizing the code easier.\n\t\tcollector.timeoutChannel = make(chan time.Time)\n\t}\n\n\t// Configure a new FileBeat Prospector with our rawConfig that will send it's data to a\n\t// CollectorOutleter\n\tp, err := prospector.NewProspector(\n\t\trawConfig,\n\t\tcollector.collectorOutleterFactory,\n\t\tcollector.prospectorDone,\n\t\t[]file.State{},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcollector.prospector = p\n\treturn &collector, nil\n}", "func New(client *statsd.Client, interval time.Duration) *Collector {\n\treturn &Collector{\n\t\tinterval: interval,\n\t\tclient: client,\n\t\tdone: make(chan struct{}),\n\t}\n}", "func NewCollector(cfg *config.AgentConfig, ctx context.Context) (Collector, error) {\n\tsysInfo, err := checks.CollectSystemInfo(cfg)\n\tif err != nil {\n\t\treturn Collector{}, err\n\t}\n\n\tenabledChecks := make([]checks.Check, 0)\n\tfor _, c := range checks.All {\n\t\tif cfg.CheckIsEnabled(c.Name()) {\n\t\t\tc.Init(cfg, sysInfo)\n\t\t\tenabledChecks = append(enabledChecks, c)\n\t\t}\n\t}\n\n\treturn NewCollectorWithChecks(cfg, enabledChecks, ctx), nil\n}", "func NewCollector(bindIP, port string) (*SyslogCollector, error) {\n\tdefer TRA(CE())\n\tchannel := make(syslog.LogPartsChannel)\n\tsysServ := syslog.NewServer()\n\tsysServ.SetHandler(syslog.NewChannelHandler(channel))\n\t// uses RFC3164 because it is default for rsyslog\n\tsysServ.SetFormat(syslog.RFC3164)\n\terr := sysServ.ListenUDP(fmt.Sprintf(\"%s:%s\", bindIP, port))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgo func(channel syslog.LogPartsChannel) {\n\t\tfor logEntry := range channel {\n\t\t\tinfo, err := ctl.NewHostInfo()\n\t\t\tif err != nil {\n\t\t\t\tinfo = &ctl.HostInfo{}\n\t\t\t}\n\t\t\tevent, err := ctl.NewEvent(logEntry, *info)\n\t\t\tif err != nil {\n\t\t\t\tErrorLogger.Printf(\"cannot format syslog entry: %s\\n\", err)\n\t\t\t}\n\t\t\terr = event.Save(SubmitPath())\n\t\t\tif err != nil {\n\t\t\t\tErrorLogger.Printf(\"cannot save syslog entry to file: %s\\n\", err)\n\t\t\t}\n\t\t}\n\t}(channel)\n\treturn &SyslogCollector{\n\t\tserver: sysServ,\n\t\tport: port,\n\t}, nil\n}", "func New(computeAPI ComputeAPI, dnsAPI DNSAPI, removalPredicate IPAddressRemovalPredicate) *Collector {\n\treturn &Collector{computeAPI, dnsAPI, removalPredicate}\n}", "func NewCollector(apiKey, hmacKey string) (*Collector, error) {\n\thmacKeyBuf, err := hex.DecodeString(hmacKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"parsing hmac key: %v\", err)\n\t}\n\tbaseURL := IngestionBaseURL\n\thost := os.Getenv(\"EI_HOST\")\n\tif host == \"localhost\" {\n\t\tbaseURL = \"http://localhost:4810\"\n\t} else if strings.HasSuffix(host, \"test.edgeimpulse.com\") {\n\t\tbaseURL = \"http://ingestion.\" + host\n\t} else if strings.HasSuffix(host, \"edgeimpulse.com\") {\n\t\tbaseURL = \"https://ingestion.\" + host\n\t}\n\tc := &Collector{http.DefaultClient, baseURL, hmacKeyBuf, apiKey}\n\treturn c, nil\n}", "func New() Collector {\n\treturn &collector{\n\t\tinner: sigar.ConcreteSigar{},\n\t}\n}", "func NewCollect() *cobra.Command {\n\tcollectOptions := newCollectOptions()\n\n\tcmd := &cobra.Command{\n\t\tUse: \"collect\",\n\t\tShort: \"Obtain all the data of the current node\",\n\t\tLong: edgecollectLongDescription,\n\t\tExample: edgecollectExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\terr := ExecuteCollect(collectOptions)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t}\n\t\t},\n\t}\n\tcmd.AddCommand()\n\taddCollectOtherFlags(cmd, collectOptions)\n\treturn cmd\n}", "func New(cfg Collector, nodeInfo collectors.NodeInfo, rels *ContainerTaskRels) (Collector, chan producers.MetricsMessage) {\n\tc := cfg\n\tc.log = logrus.WithFields(logrus.Fields{\"collector\": \"mesos-agent\"})\n\tc.nodeInfo = nodeInfo\n\tc.metricsChan = make(chan producers.MetricsMessage)\n\tc.ContainerTaskRels = rels\n\treturn c, c.metricsChan\n}", "func NewCollectServer(cfg *ServerConfig) *CollectServer {\n\tserver := &CollectServer{Config: cfg}\n\tlogger := logrus.New()\n\tlogger.Out = cfg.LogCfg.Output\n\tlogger.Level = cfg.LogCfg.Level\n\tlogger.Formatter = cfg.LogCfg.Format\n\tserver.Logger = logger\n\treturn server\n}", "func NewStatsCollector(cliContext *cli.Context) (*StatsCollector, error) {\n\n\t// fill the Collector struct\n\tcollector := &StatsCollector{\n\t\tcliContext: cliContext,\n\t\tsocketPath: cliContext.String(\"socketPath\"),\n\t\tkamailioHost: cliContext.String(\"host\"),\n\t\tkamailioPort: cliContext.Int(\"port\"),\n\t}\n\n\t// fine, return the created object struct\n\treturn collector, nil\n}", "func NewCollector() (prometheus.Collector, error) {\n\treturn &collector{}, nil\n}", "func NewCollector(dyno *Dynomite) *Collector {\n\treturn &Collector{\n\t\tdyno: dyno,\n\t\tstate: typedDesc{\n\t\t\tdesc: prometheus.NewDesc(\n\t\t\t\t\"dynomite_state\",\n\t\t\t\t\"State as reported by Dynomite.\",\n\t\t\t\t[]string{\"state\", \"rack\", \"dc\", \"token\", \"ip_address\"}, nil),\n\t\t\tvalueType: prometheus.GaugeValue,\n\t\t},\n\t\tdbSize: typedDesc{\n\t\t\tdesc: prometheus.NewDesc(\n\t\t\t\t\"dynomite_db_size\",\n\t\t\t\t\"Key database size as reported by the Redis backend.\",\n\t\t\t\t[]string{\"rack\", \"dc\", \"token\", \"ip_address\"}, nil),\n\t\t\tvalueType: prometheus.GaugeValue,\n\t\t},\n\t\tuptime: typedDesc{\n\t\t\tdesc: prometheus.NewDesc(\n\t\t\t\t\"dynomite_uptime\",\n\t\t\t\t\"Uptime as reported by Dynomite info.\",\n\t\t\t\t[]string{\"rack\", \"dc\", \"token\", \"ip_address\"}, nil),\n\t\t\tvalueType: prometheus.GaugeValue,\n\t\t},\n\t\tclientConnections: typedDesc{\n\t\t\tdesc: prometheus.NewDesc(\n\t\t\t\t\"dynomite_client_connections\",\n\t\t\t\t\"Client connections as reported by Dynomite info.\",\n\t\t\t\t[]string{\"rack\", \"dc\", \"token\", \"ip_address\"}, nil),\n\t\t\tvalueType: prometheus.GaugeValue,\n\t\t},\n\t\tclientReadRequests: typedDesc{\n\t\t\tdesc: prometheus.NewDesc(\n\t\t\t\t\"dynomite_client_read_requests\",\n\t\t\t\t\"Client read requests as reported by Dynomite info.\",\n\t\t\t\t[]string{\"rack\", \"dc\", \"token\", \"ip_address\"}, nil),\n\t\t\tvalueType: prometheus.GaugeValue,\n\t\t},\n\t\tclientWriteRequests: typedDesc{\n\t\t\tdesc: prometheus.NewDesc(\n\t\t\t\t\"dynomite_client_write_requests\",\n\t\t\t\t\"Client write requests as reported by Dynomite info.\",\n\t\t\t\t[]string{\"rack\", \"dc\", \"token\", \"ip_address\"}, nil),\n\t\t\tvalueType: prometheus.GaugeValue,\n\t\t},\n\t\tclientDroppedRequests: typedDesc{\n\t\t\tdesc: prometheus.NewDesc(\n\t\t\t\t\"dynomite_client_dropped_requests\",\n\t\t\t\t\"Client dropped requests as reported by Dynomite info.\",\n\t\t\t\t[]string{\"rack\", \"dc\", \"token\", \"ip_address\"}, nil),\n\t\t\tvalueType: prometheus.GaugeValue,\n\t\t},\n\t}\n}", "func NewVMwareCollector(ctx *pulumi.Context,\n\tname string, args *VMwareCollectorArgs, opts ...pulumi.ResourceOption) (*VMwareCollector, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.ProjectName == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'ProjectName'\")\n\t}\n\tif args.ResourceGroupName == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'ResourceGroupName'\")\n\t}\n\taliases := pulumi.Aliases([]pulumi.Alias{\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:migrate:VMwareCollector\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-native:migrate/v20191001:VMwareCollector\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:migrate/v20191001:VMwareCollector\"),\n\t\t},\n\t})\n\topts = append(opts, aliases)\n\tvar resource VMwareCollector\n\terr := ctx.RegisterResource(\"azure-native:migrate:VMwareCollector\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (o *PostAutoDiscoveryPingsweepParams) SetRemoteCollectorID(remoteCollectorID *int64) {\n\to.RemoteCollectorID = remoteCollectorID\n}", "func newMemoryConnection(\n\tlogger log.Logger,\n\tlocalID types.NodeID,\n\tremoteID types.NodeID,\n\treceiveCh <-chan memoryMessage,\n\tsendCh chan<- memoryMessage,\n) *MemoryConnection {\n\treturn &MemoryConnection{\n\t\tlogger: logger.With(\"remote\", remoteID),\n\t\tlocalID: localID,\n\t\tremoteID: remoteID,\n\t\treceiveCh: receiveCh,\n\t\tsendCh: sendCh,\n\t}\n}", "func NewFileCollector(config []byte) (Collector, error) {\n\tslaunch.Debug(\"New Files Collector initialized\\n\")\n\tvar fc = new(FileCollector)\n\terr := json.Unmarshal(config, &fc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn fc, nil\n}", "func NewCollector(cm *clientmanager.ClientManager) prometheus.Collector {\n\treturn &grpcClientManagerCollector{\n\t\tcm: cm,\n\t}\n}", "func (c *ClusterScalingScheduleCollectorPlugin) NewCollector(hpa *autoscalingv2.HorizontalPodAutoscaler, config *MetricConfig, interval time.Duration) (Collector, error) {\n\treturn NewClusterScalingScheduleCollector(c.store, c.defaultScalingWindow, c.defaultTimeZone, c.rampSteps, c.now, hpa, config, interval)\n}", "func newPoolCollector(config monitoring.MetricsConfig, logger *zap.Logger,\n\tspectrumClient spectrumservice.Client) (Collector, error) {\n\n\tlabelPool := []string{\"pool_name\", \"storage_system\"}\n\n\tproperties := make(map[string]*prometheus.Desc)\n\n\tfor _, p := range config.Metrics.Pools.Properties {\n\t\tproperties[p.PropertyName] = prometheus.NewDesc(p.PrometheusName, p.PrometheusHelp, labelPool, nil)\n\t}\n\n\treturn &poolCollector{\n\t\tibmSpectrumClient: spectrumClient,\n\t\tlogger: logger.Sugar(),\n\t\tproperties: properties,\n\t}, nil\n}", "func NewLocalAmboyStatsCollector(env cedar.Environment, id string) amboy.Job {\n\tj := makeAmboyStatsCollector()\n\tj.ExcludeRemote = true\n\tj.env = env\n\tj.SetID(fmt.Sprintf(\"%s-%s\", amboyStatsCollectorJobName, id))\n\treturn j\n}", "func NewFileCollector(name string, limit Size, pipe bool) File {\n\treturn &FileCollector{Name: name, Limit: limit, Pipe: pipe}\n}", "func NewCollector(url, token, xSecret string) (*Collector, error) {\n\tc := Collector{}\n\n\tif url == \"\" {\n\t\treturn nil, fmt.Errorf(\"URL should not be empty\")\n\t}\n\tc.dadataAPIURL = url\n\tif token == \"\" {\n\t\treturn nil, fmt.Errorf(\"Token should not be empty. Please specify it via DADATA_TOKEN env var\")\n\t}\n\tc.dadataToken = token\n\tif xSecret == \"\" {\n\t\treturn nil, fmt.Errorf(\"X-Secret should not be empty. Please specify it via DADATA_X_SECRET env var\")\n\t}\n\tc.dadataXSecret = xSecret\n\n\terr := c.dadataCheck()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc.totalScrapes = prometheus.NewCounter(prometheus.CounterOpts{\n\t\tNamespace: namespace,\n\t\tName: \"exporter_scrapes_total\",\n\t\tHelp: \"Count of total scrapes\",\n\t})\n\n\tc.failedBalanceScrapes = prometheus.NewCounter(prometheus.CounterOpts{\n\t\tNamespace: namespace,\n\t\tName: \"exporter_failed_balance_scrapes_total\",\n\t\tHelp: \"Count of failed balance scrapes\",\n\t})\n\n\tc.failedStatsScrapes = prometheus.NewCounter(prometheus.CounterOpts{\n\t\tNamespace: namespace,\n\t\tName: \"exporter_failed_stats_scrapes_total\",\n\t\tHelp: \"Count of failed stats scrapes\",\n\t})\n\n\tc.CurrentBalance = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace: namespace,\n\t\tName: \"current_balance\",\n\t\tHelp: \"Current balance on Dadata\",\n\t})\n\n\tc.ServicesMerging = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: \"services\",\n\t\tName: \"merging_total\",\n\t\tHelp: \"Merging count for today\",\n\t})\n\n\tc.ServicesSuggestions = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: \"services\",\n\t\tName: \"suggestions_total\",\n\t\tHelp: \"Suggestions count for today\",\n\t})\n\n\tc.ServicesClean = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: \"services\",\n\t\tName: \"clean_total\",\n\t\tHelp: \"Clean count for today\",\n\t})\n\n\treturn &c, nil\n}", "func new(config map[string]any, endpoint *fd.FD) (seccheck.Sink, error) {\n\tif endpoint == nil {\n\t\treturn nil, fmt.Errorf(\"remote sink requires an endpoint\")\n\t}\n\tr := &remote{\n\t\tendpoint: endpoint,\n\t\tinitialBackoff: 25 * time.Microsecond,\n\t\tmaxBackoff: 10 * time.Millisecond,\n\t}\n\tif retriesOpaque, ok := config[\"retries\"]; ok {\n\t\tretries, ok := retriesOpaque.(float64)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"retries %q is not an int\", retriesOpaque)\n\t\t}\n\t\tr.retries = int(retries)\n\t\tif float64(r.retries) != retries {\n\t\t\treturn nil, fmt.Errorf(\"retries %q is not an int\", retriesOpaque)\n\t\t}\n\t}\n\tif ok, backoff, err := parseDuration(config, \"backoff\"); err != nil {\n\t\treturn nil, err\n\t} else if ok {\n\t\tr.initialBackoff = backoff\n\t}\n\tif ok, backoff, err := parseDuration(config, \"backoff_max\"); err != nil {\n\t\treturn nil, err\n\t} else if ok {\n\t\tr.maxBackoff = backoff\n\t}\n\tif r.initialBackoff > r.maxBackoff {\n\t\treturn nil, fmt.Errorf(\"initial backoff (%v) cannot be larger than max backoff (%v)\", r.initialBackoff, r.maxBackoff)\n\t}\n\n\tlog.Debugf(\"Remote sink created, endpoint FD: %d, %+v\", r.endpoint.FD(), r)\n\treturn r, nil\n}", "func NewRemote(v gointerfaces.Version, logger log.Logger, remoteKV remote.KVClient) remoteOpts {\n\treturn remoteOpts{bucketsCfg: mdbx.WithChaindataTables, version: v, log: logger, remoteKV: remoteKV}\n}", "func newRPCServer(parallelTotal int, reporter reporters.Reporter) (*RPCServer, error) {\n\tlistener, err := net.Listen(\"tcp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &RPCServer{\n\t\tlistener: listener,\n\t\thandler: newServerHandler(parallelTotal, reporter),\n\t}, nil\n}", "func (c *ScalingScheduleCollectorPlugin) NewCollector(hpa *autoscalingv2.HorizontalPodAutoscaler, config *MetricConfig, interval time.Duration) (Collector, error) {\n\treturn NewScalingScheduleCollector(c.store, c.defaultScalingWindow, c.defaultTimeZone, c.rampSteps, c.now, hpa, config, interval)\n}", "func NewVaultCollector() (Collector, error) {\n\taddr := os.Getenv(\"VAULT_ADDR\")\n\tcaCert := os.Getenv(\"VAULT_CACERT\")\n\tcaPath := os.Getenv(\"VAULT_CAPATH\")\n\tserverName := \"\"\n\tif addr != \"\" {\n\t\turl, err := url.Parse(addr)\n\t\tif err != nil {\n\t\t\treturn nil, maskAny(err)\n\t\t}\n\t\thost, _, err := net.SplitHostPort(url.Host)\n\t\tif err != nil {\n\t\t\treturn nil, maskAny(err)\n\t\t}\n\t\tserverName = host\n\t}\n\tvar certPool *x509.CertPool\n\tif caCert != \"\" || caPath != \"\" {\n\t\tvar err error\n\t\tif caCert != \"\" {\n\t\t\tlog.Debugf(\"Loading CA cert: %s\", caCert)\n\t\t\tcertPool, err = LoadCACert(caCert)\n\t\t} else {\n\t\t\tlog.Debugf(\"Loading CA certs from: %s\", caPath)\n\t\t\tcertPool, err = LoadCAPath(caPath)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, maskAny(err)\n\t\t}\n\t}\n\n\ttransport := cleanhttp.DefaultTransport()\n\ttransport.Proxy = nil\n\ttransport.TLSClientConfig = &tls.Config{\n\t\tServerName: serverName,\n\t\tRootCAs: certPool,\n\t\t//InsecureSkipVerify: true,\n\t}\n\tclient := &http.Client{\n\t\tTransport: transport,\n\t}\n\tc := &vaultCollector{\n\t\taddress: addr,\n\t\tclient: client,\n\t\tvaultUnsealedDesc: prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(vaultNamespace, \"\", \"server_unsealed\"),\n\t\t\t\"Vault unseal status (1=unsealed, 0=sealed)\", []string{\"address\"}, nil,\n\t\t),\n\t\tstatus: make(map[string]float64),\n\t}\n\tgo c.updateStatusLoop()\n\treturn c, nil\n}", "func newCollectionStatsCollector(ctx context.Context, client *mongo.Client, logger *logrus.Logger, compatible, discovery bool, topology labelsGetter, collections []string) *collstatsCollector {\n\treturn &collstatsCollector{\n\t\tctx: ctx,\n\t\tbase: newBaseCollector(client, logger),\n\n\t\tcompatibleMode: compatible,\n\t\tdiscoveringMode: discovery,\n\t\ttopologyInfo: topology,\n\n\t\tcollections: collections,\n\t}\n}", "func NewHTTPCollector(url string, options ...HTTPOption) (Collector, error) {\n\tc := &HTTPCollector{\n\t\tlogger: NewNopLogger(),\n\t\turl: url,\n\t\tclient: &http.Client{Timeout: defaultHTTPTimeout},\n\t\tbatchInterval: defaultHTTPBatchInterval * time.Second,\n\t\tbatchSize: defaultHTTPBatchSize,\n\t\tbatch: []*zipkincore.Span{},\n\t\tspanc: make(chan *zipkincore.Span, defaultHTTPBatchSize),\n\t\tquit: make(chan struct{}, 1),\n\t\tshutdown: make(chan error, 1),\n\t\tbatchPool: sync.Pool{\n\t\t\tNew: func() interface{} {\n\t\t\t\treturn make([]*zipkincore.Span, 0, defaultHTTPBatchSize)\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, option := range options {\n\t\toption(c)\n\t}\n\n\tgo c.loop()\n\treturn c, nil\n}", "func NewInfluxCollector(user, pass, addr string) (Collector, error) {\n\tc, err := client.NewHTTPClient(client.HTTPConfig{\n\t\tAddr: addr,\n\t\tUsername: user,\n\t\tPassword: pass,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinput := make(chan Collectable, 10)\n\n\tic := &InfluxCollector{\n\t\tclient: c,\n\t\tlock: &sync.RWMutex{},\n\t\tinput: input,\n\t\tlogger: log.Logger(context.Background()).Named(\"collector_influx\"),\n\t\t// TODO fix the point aggregation and find a sane batch size\n\t\tbatchSize: 1,\n\t\tbatchConfig: client.BatchPointsConfig{\n\t\t\tDatabase: databaseName,\n\t\t\tPrecision: \"ns\",\n\t\t},\n\t\ttimeout: 1000 * time.Millisecond,\n\t}\n\n\t// Create the database\n\tif err := ic.createDB(databaseName); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Initialize the processor\n\tgo ic.processor(context.Background(), input)\n\n\treturn ic, nil\n}", "func NewCollector(defaultGroup string) *MemoryMetricsCollector {\n\treturn &MemoryMetricsCollector{defaultGroup: defaultGroup, metrics: make([]operation.MetricOperation, 0)}\n}", "func NewCollector(ctx context.Context, cc *collector.CollectorContext, collectDuration prometheus.Observer) prometheus.Collector {\n\treturn &StorageDomainCollector{\n\t\trootCtx: ctx,\n\t\tcc: cc,\n\t\tcollectDuration: collectDuration,\n\t}\n}", "func (c *SkipperCollectorPlugin) NewCollector(hpa *autoscalingv2.HorizontalPodAutoscaler, config *MetricConfig, interval time.Duration) (Collector, error) {\n\tif strings.HasPrefix(config.Metric.Name, rpsMetricName) {\n\t\tbackend, ok := config.Config[\"backend\"]\n\t\tif !ok {\n\t\t\t// TODO: remove the deprecated way of specifying\n\t\t\t// optional backend at a later point in time.\n\t\t\tif len(config.Metric.Name) > len(rpsMetricName) {\n\t\t\t\tmetricNameParts := strings.Split(config.Metric.Name, rpsMetricBackendSeparator)\n\t\t\t\tif len(metricNameParts) == 2 {\n\t\t\t\t\tbackend = metricNameParts[1]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn NewSkipperCollector(c.client, c.rgClient, c.plugin, hpa, config, interval, c.backendAnnotations, backend)\n\t}\n\treturn nil, fmt.Errorf(\"metric '%s' not supported\", config.Metric.Name)\n}", "func (*noOpConntracker) Collect(ch chan<- prometheus.Metric) {}", "func New(config Config) (*Collector, error) {\n\tif config.Logger == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"%T.Logger must not be empty\", config)\n\t}\n\n\tif config.IFace == \"\" {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"%T.IFace must not be empty\", config)\n\t}\n\n\tcollector := &Collector{\n\t\tiface: config.IFace,\n\t}\n\n\tnicStats, err := ethtool.Stats(collector.iface)\n\tif err != nil {\n\t\treturn nil, microerror.Mask(err)\n\t}\n\n\tcollector.metrics = make(map[string]*prometheus.Desc)\n\tfor label, _ := range nicStats {\n\t\tfqName := prometheus.BuildFQName(nic_metric_namespace, \"\", label)\n\t\tcollector.metrics[label] = prometheus.NewDesc(fqName, fmt.Sprintf(\"Generated description for metric %#q\", label), []string{\"iface\"}, nil)\n\t}\n\n\treturn collector, nil\n}", "func newRemoteLoggingClient(ctx context.Context, conn *grpc.ClientConn) (*remoteLoggingClient, error) {\n\tcl := protocol.NewLoggingClient(conn)\n\tstream, err := cl.ReadLogs(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Read the initial response to check success and make sure we have been\n\t// subscribed to logs.\n\tif _, err := stream.Recv(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tl := &remoteLoggingClient{\n\t\tstream: stream,\n\t\tdoneCh: make(chan struct{}),\n\t}\n\n\t// Start a goroutine to call logger for every received ReadLogsResponse.\n\tgo l.runBackground(ctx)\n\n\treturn l, nil\n}", "func NewNVMeCollector(logger log.Logger) (Collector, error) {\n\tfs, err := sysfs.NewFS(*sysPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to open sysfs: %w\", err)\n\t}\n\n\treturn &nvmeCollector{\n\t\tfs: fs,\n\t\tlogger: logger,\n\t}, nil\n}", "func NewUpgradeCollector(c client.Client) (prometheus.Collector, error) {\n\tupgradeConfigManager, err := upgradeconfigmanager.NewBuilder().NewManager(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmanagedMetrics := bootstrapMetrics()\n\n\treturn &UpgradeCollector{\n\t\tupgradeConfigManager,\n\t\tcv.NewCVClient(c),\n\t\tmanagedMetrics,\n\t}, nil\n}", "func NewMultiCollector(collectors ...Collector) Collector {\n\tif len(collectors) == 1 {\n\t\treturn collectors[0]\n\t}\n\treturn MultiCollector(collectors)\n}", "func NewTChanCollectorServer(handler TChanCollector) thrift.TChanServer {\n\treturn &tchanCollectorServer{\n\t\thandler,\n\t}\n}", "func NewLibvirtCollector() *Libvirt {\n\treturn &Libvirt{}\n\n}", "func NewLocalRouterCollector(ctx context.Context, logger *slog.Logger, errors *prometheus.CounterVec, client platform.LocalRouterClient) *LocalRouterCollector {\n\terrors.WithLabelValues(\"local_router\").Add(0)\n\n\tlocalRouterLabels := []string{\"id\", \"name\"}\n\tlocalRouterInfoLabels := append(localRouterLabels, \"tags\", \"description\")\n\tlocalRouterSwitchInfoLabels := append(localRouterLabels, \"category\", \"code\", \"zone_id\")\n\tlocalRouterServerNetworkInfoLabels := append(localRouterLabels, \"vip\", \"ipaddress1\", \"ipaddress2\", \"nw_mask_len\", \"vrid\")\n\tlocalRouterPeerLabels := append(localRouterLabels, \"peer_index\", \"peer_id\")\n\tlocalRouterPeerInfoLabels := append(localRouterPeerLabels, \"enabled\", \"description\")\n\tlocalRouterStaticRouteInfoLabels := append(localRouterLabels, \"route_index\", \"prefix\", \"next_hop\")\n\n\treturn &LocalRouterCollector{\n\t\tctx: ctx,\n\t\tlogger: logger,\n\t\terrors: errors,\n\t\tclient: client,\n\t\tUp: prometheus.NewDesc(\n\t\t\t\"sakuracloud_local_router_up\",\n\t\t\t\"If 1 the LocalRouter is available, 0 otherwise\",\n\t\t\tlocalRouterLabels, nil,\n\t\t),\n\t\tLocalRouterInfo: prometheus.NewDesc(\n\t\t\t\"sakuracloud_local_router_info\",\n\t\t\t\"A metric with a constant '1' value labeled by localRouter information\",\n\t\t\tlocalRouterInfoLabels, nil,\n\t\t),\n\t\tSwitchInfo: prometheus.NewDesc(\n\t\t\t\"sakuracloud_local_router_switch_info\",\n\t\t\t\"A metric with a constant '1' value labeled by localRouter connected switch information\",\n\t\t\tlocalRouterSwitchInfoLabels, nil,\n\t\t),\n\t\tNetworkInfo: prometheus.NewDesc(\n\t\t\t\"sakuracloud_local_router_network_info\",\n\t\t\t\"A metric with a constant '1' value labeled by network information of the localRouter\",\n\t\t\tlocalRouterServerNetworkInfoLabels, nil,\n\t\t),\n\t\tPeerInfo: prometheus.NewDesc(\n\t\t\t\"sakuracloud_local_router_peer_info\",\n\t\t\t\"A metric with a constant '1' value labeled by peer information\",\n\t\t\tlocalRouterPeerInfoLabels, nil,\n\t\t),\n\t\tPeerUp: prometheus.NewDesc(\n\t\t\t\"sakuracloud_local_router_peer_up\",\n\t\t\t\"If 1 the Peer is available, 0 otherwise\",\n\t\t\tlocalRouterPeerLabels, nil,\n\t\t),\n\t\tStaticRouteInfo: prometheus.NewDesc(\n\t\t\t\"sakuracloud_local_router_static_route_info\",\n\t\t\t\"A metric with a constant '1' value labeled by static route information\",\n\t\t\tlocalRouterStaticRouteInfoLabels, nil,\n\t\t),\n\t\tReceiveBytesPerSec: prometheus.NewDesc(\n\t\t\t\"sakuracloud_local_router_receive_per_sec\",\n\t\t\t\"Receive bytes per seconds\",\n\t\t\tlocalRouterLabels, nil,\n\t\t),\n\t\tSendBytesPerSec: prometheus.NewDesc(\n\t\t\t\"sakuracloud_local_router_send_per_sec\",\n\t\t\t\"Send bytes per seconds\",\n\t\t\tlocalRouterLabels, nil,\n\t\t),\n\t}\n}", "func NewRGWCollector(exporter *Exporter, background bool) *RGWCollector {\n\tlabels := make(prometheus.Labels)\n\tlabels[\"cluster\"] = exporter.Cluster\n\n\trgw := &RGWCollector{\n\t\tconfig: exporter.Config,\n\t\tbackground: background,\n\t\tlogger: exporter.Logger,\n\t\tgetRGWGCTaskList: rgwGetGCTaskList,\n\n\t\tActiveTasks: prometheus.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: cephNamespace,\n\t\t\t\tName: \"rgw_gc_active_tasks\",\n\t\t\t\tHelp: \"RGW GC active task count\",\n\t\t\t\tConstLabels: labels,\n\t\t\t},\n\t\t\t[]string{},\n\t\t),\n\t\tActiveObjects: prometheus.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: cephNamespace,\n\t\t\t\tName: \"rgw_gc_active_objects\",\n\t\t\t\tHelp: \"RGW GC active object count\",\n\t\t\t\tConstLabels: labels,\n\t\t\t},\n\t\t\t[]string{},\n\t\t),\n\t\tPendingTasks: prometheus.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: cephNamespace,\n\t\t\t\tName: \"rgw_gc_pending_tasks\",\n\t\t\t\tHelp: \"RGW GC pending task count\",\n\t\t\t\tConstLabels: labels,\n\t\t\t},\n\t\t\t[]string{},\n\t\t),\n\t\tPendingObjects: prometheus.NewGaugeVec(\n\t\t\tprometheus.GaugeOpts{\n\t\t\t\tNamespace: cephNamespace,\n\t\t\t\tName: \"rgw_gc_pending_objects\",\n\t\t\t\tHelp: \"RGW GC pending object count\",\n\t\t\t\tConstLabels: labels,\n\t\t\t},\n\t\t\t[]string{},\n\t\t),\n\t}\n\n\tif rgw.background {\n\t\t// rgw stats need to be collected in the background as this can take a while\n\t\t// if we have a large backlog\n\t\tgo rgw.backgroundCollect()\n\t}\n\n\treturn rgw\n}", "func NewCollector() collector.RPCCollector {\n\treturn &accountingCollector{}\n}", "func NewRemoteFlowProvider(config *util.ServiceConfig, embeddedFlowMgr *support.EmbeddedFlowManager) *RemoteFlowProvider {\n\n\tvar service RemoteFlowProvider\n\tservice.flowCache = make(map[string]*flowdef.Definition)\n\tservice.mutex = &sync.Mutex{}\n\tservice.enabled = config.Enabled\n\tservice.embeddedMgr = embeddedFlowMgr\n\treturn &service\n}", "func NewFileCollector() FileCollector {\n\treturn make(FileCollector)\n}", "func New(chainID, remote string) (provider.Provider, error) {\n\thttpClient, err := rpcclient.NewHTTP(remote, \"/websocket\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewWithClient(chainID, httpClient), nil\n}", "func NewRemoteReplicator(\n\tctx context.Context,\n\tchannel *ReplicatorChannel,\n\tstateMgr storage.StateManager,\n\tcliFct rpc.ClientStreamFactory,\n) Replicator {\n\tr := &remoteReplicator{\n\t\tctx: ctx,\n\t\treplicator: replicator{\n\t\t\tchannel: channel,\n\t\t},\n\t\tcliFct: cliFct,\n\t\tstateMgr: stateMgr,\n\t\tisSuspend: atomic.NewBool(false),\n\t\tsuspend: make(chan struct{}),\n\t\tstatistics: metrics.NewStorageRemoteReplicatorStatistics(channel.State.Database, channel.State.ShardID.String()),\n\t\tlogger: logger.GetLogger(\"Replica\", \"RemoteReplicator\"),\n\t}\n\tr.state.Store(&state{state: models.ReplicatorInitState, errMsg: \"replicator initialized\"})\n\n\t// watch follower node state change\n\tstateMgr.WatchNodeStateChangeEvent(channel.State.Follower, r.handleNodeStateChangeEvent)\n\n\tr.logger.Info(\"start remote replicator\", logger.String(\"replica\", r.String()))\n\treturn r\n}", "func New(logger logrus.FieldLogger, conf Config) (*Collector, error) {\n\tproducer, err := sarama.NewSyncProducer(conf.Brokers, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Collector{\n\t\tProducer: producer,\n\t\tConfig: conf,\n\t\tlogger: logger,\n\t}, nil\n}", "func New() *IpmiCollector {\n\tcollector := &IpmiCollector{Initialized: false}\n\treturn collector\n}", "func createRemoteReadServer(t *testing.T, seriesToBeSent []prompb.TimeSeries) (*remoteReadServer, string) {\n\ts := httptest.NewServer(getReadHandler(t, seriesToBeSent))\n\treturn &remoteReadServer{\n\t\tserver: s,\n\t\tseries: seriesToBeSent,\n\t}, s.URL\n}", "func NewMetricCollector(logger *zap.SugaredLogger) *MetricCollector {\n\tcollector := &MetricCollector{\n\t\tlogger: logger,\n\t\tcollections: make(map[string]*collection),\n\t}\n\n\treturn collector\n}", "func NewNFSCollector(g getNFSStats) *nfsCollector {\n\treturn &nfsCollector{\n\t\tg,\n\t}\n}", "func NewSyncCollector() *SyncCollector {\n\tso := SyncCollector{c: make(Collector)}\n\treturn &so\n}", "func (p *LightningPool) new(ctx context.Context) (*amqp.Channel, error) {\n\treturn p.conn.Channel(ctx)\n}", "func New() *CPUCollector {\n\tcpuMetrics := newCPUMetrics()\n\tcpuStats := cpuclient.New()\n\n\treturn &CPUCollector{\n\t\tcpuMetrics: cpuMetrics,\n\t\tcpuStats: cpuStats,\n\t}\n}", "func New(\n\tlogger logrus.FieldLogger,\n\tconf Config, src *loader.SourceData, opts lib.Options, executionPlan []lib.ExecutionStep, version string,\n) (*Collector, error) {\n\tif err := MergeFromExternal(opts.External, &conf); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif conf.AggregationPeriod.Duration > 0 && (opts.SystemTags.Has(stats.TagVU) || opts.SystemTags.Has(stats.TagIter)) {\n\t\treturn nil, errors.New(\"Aggregation cannot be enabled if the 'vu' or 'iter' system tag is also enabled\")\n\t}\n\n\tif !conf.Name.Valid || conf.Name.String == \"\" {\n\t\tconf.Name = null.StringFrom(filepath.Base(src.URL.String()))\n\t}\n\tif conf.Name.String == \"-\" {\n\t\tconf.Name = null.StringFrom(TestName)\n\t}\n\n\tthresholds := make(map[string][]*stats.Threshold)\n\tfor name, t := range opts.Thresholds {\n\t\tthresholds[name] = append(thresholds[name], t.Thresholds...)\n\t}\n\n\tduration, testEnds := lib.GetEndOffset(executionPlan)\n\tif !testEnds {\n\t\treturn nil, errors.New(\"tests with unspecified duration are not allowed when outputting data to k6 cloud\")\n\t}\n\n\tif !conf.Token.Valid && conf.DeprecatedToken.Valid {\n\t\tlogger.Warn(\"K6CLOUD_TOKEN is deprecated and will be removed. Use K6_CLOUD_TOKEN instead.\")\n\t\tconf.Token = conf.DeprecatedToken\n\t}\n\n\tif !(conf.MetricPushConcurrency.Int64 > 0) {\n\t\treturn nil, errors.Errorf(\"metrics push concurrency must be a positive number but is %d\",\n\t\t\tconf.MetricPushConcurrency.Int64)\n\t}\n\n\tif !(conf.MaxMetricSamplesPerPackage.Int64 > 0) {\n\t\treturn nil, errors.Errorf(\"metric samples per package must be a positive number but is %d\",\n\t\t\tconf.MaxMetricSamplesPerPackage.Int64)\n\t}\n\n\treturn &Collector{\n\t\tconfig: conf,\n\t\tthresholds: thresholds,\n\t\tclient: NewClient(logger, conf.Token.String, conf.Host.String, version),\n\t\tanonymous: !conf.Token.Valid,\n\t\texecutionPlan: executionPlan,\n\t\tduration: int64(duration / time.Second),\n\t\topts: opts,\n\t\taggrBuckets: map[int64]map[[3]string]aggregationBucket{},\n\t\tstopSendingMetricsCh: make(chan struct{}),\n\t\tlogger: logger,\n\t}, nil\n}", "func New(meta interface{}) *Broadcaster {\n\tlistenc := make(chan (chan (chan broadcast)))\n\tsendc := make(chan interface{})\n\tgo func() {\n\t\tcurrc := make(chan broadcast, 1)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase v, ok := <-sendc:\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tc := make(chan broadcast, 1)\n\t\t\t\tb := broadcast{c: c, v: v}\n\t\t\t\tcurrc <- b\n\t\t\t\tcurrc = c\n\t\t\tcase r := <-listenc:\n\t\t\t\tr <- currc\n\t\t\t}\n\t\t}\n\t}()\n\treturn &Broadcaster{\n\t\tlistenc: listenc,\n\t\tSendc: sendc,\n\t\tvalueType: reflect.TypeOf(meta),\n\t}\n}", "func (t *OpenconfigSystem_System_Logging_RemoteServers) NewRemoteServer(Host string) (*OpenconfigSystem_System_Logging_RemoteServers_RemoteServer, error){\n\n\t// Initialise the list within the receiver struct if it has not already been\n\t// created.\n\tif t.RemoteServer == nil {\n\t\tt.RemoteServer = make(map[string]*OpenconfigSystem_System_Logging_RemoteServers_RemoteServer)\n\t}\n\n\tkey := Host\n\n\t// Ensure that this key has not already been used in the\n\t// list. Keyed YANG lists do not allow duplicate keys to\n\t// be created.\n\tif _, ok := t.RemoteServer[key]; ok {\n\t\treturn nil, fmt.Errorf(\"duplicate key %v for list RemoteServer\", key)\n\t}\n\n\tt.RemoteServer[key] = &OpenconfigSystem_System_Logging_RemoteServers_RemoteServer{\n\t\tHost: &Host,\n\t}\n\n\treturn t.RemoteServer[key], nil\n}", "func newAtlassianUPMCollector() *atlassianUPMCollector {\n\treturn &atlassianUPMCollector{\n\t\tatlassianUPMTimeMetric: prometheus.NewDesc(\n\t\t\tmetricNamespace+\"_collect_duration_seconds\",\n\t\t\t\"metric used to keep track of how long the \"+exporterName+\" took to Collect\",\n\t\t\t[]string{\n\t\t\t\t\"url\",\n\t\t\t},\n\t\t\tnil,\n\t\t),\n\t\tatlassianUPMUpMetric: prometheus.NewDesc(\n\t\t\tmetricNamespace+\"_rest_url_up\",\n\t\t\t\"metric used to check if the \"+exporterName+\" rest endpoint is accessible (https://<app.fqdn>/rest/plugins/1.0/), value is true if up\",\n\t\t\t[]string{\n\t\t\t\t\"url\",\n\t\t\t},\n\t\t\tnil,\n\t\t),\n\t\tatlassianUPMPlugins: prometheus.NewDesc(\n\t\t\tmetricNamespace+\"_plugin\",\n\t\t\t\"metric used to display plugin information, value is 0\",\n\t\t\t[]string{\n\t\t\t\t\"enabled\",\n\t\t\t\t\"name\",\n\t\t\t\t\"key\",\n\t\t\t\t\"installedVersion\",\n\t\t\t\t\"userInstalled\",\n\t\t\t\t\"url\",\n\t\t\t},\n\t\t\tnil,\n\t\t),\n\t\tatlassianUPMVersionsMetric: prometheus.NewDesc(\n\t\t\tmetricNamespace+\"_plugin_version_available\",\n\t\t\t\"metric used to get back the application being monitored plugin versions available, value is true if update available\",\n\t\t\t[]string{\n\t\t\t\t\"name\",\n\t\t\t\t\"key\",\n\t\t\t\t\"availableVersion\",\n\t\t\t\t\"installedVersion\",\n\t\t\t\t\"enabled\",\n\t\t\t\t\"userInstalled\",\n\t\t\t\t\"url\",\n\t\t\t},\n\t\t\tnil,\n\t\t),\n\t}\n}", "func NewVpcCollector(logger log.Logger) (Collector, error) {\n\treturn &vpcCollector{\n\t\tdesc: vpcDesc,\n\t\tlogger: logger,\n\t}, nil\n}", "func New(bufnet *bufconn.Listener) *RemotePeer {\n\tif bufnet == nil {\n\t\tbufnet = bufconn.New()\n\t}\n\n\tremote := &RemotePeer{\n\t\tbufnet: bufnet,\n\t\tsrv: grpc.NewServer(),\n\t\tCalls: make(map[string]int),\n\t}\n\n\tapi.RegisterTRISANetworkServer(remote.srv, remote)\n\tapi.RegisterTRISAHealthServer(remote.srv, remote)\n\tgo remote.srv.Serve(remote.bufnet.Sock())\n\treturn remote\n}", "func New() ([]collector.Collector, error) {\n\tnone := []collector.Collector{}\n\n\tl := log.With().Str(\"pkg\", PackageName).Logger()\n\n\tenbledCollectors := viper.GetStringSlice(config.KeyCollectors)\n\tif len(enbledCollectors) == 0 {\n\t\tl.Info().Msg(\"no builtin collectors enabled\")\n\t\treturn none, nil\n\t}\n\n\tcollectors := make([]collector.Collector, 0, len(enbledCollectors))\n\tinitErrMsg := \"initializing builtin collector\"\n\tfor _, name := range enbledCollectors {\n\t\tif !strings.HasPrefix(name, NamePrefix) {\n\t\t\tcontinue\n\t\t}\n\t\tname = strings.ReplaceAll(name, NamePrefix, \"\")\n\t\tcfgBase := \"generic_\" + name + \"_collector\"\n\t\tswitch name {\n\t\tcase NameCPU:\n\t\t\tc, err := NewCPUCollector(path.Join(defaults.EtcPath, cfgBase), l)\n\t\t\tif err != nil {\n\t\t\t\tl.Error().Str(\"name\", name).Err(err).Msg(initErrMsg)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcollectors = append(collectors, c)\n\n\t\tcase NameDisk:\n\t\t\tc, err := NewDiskCollector(path.Join(defaults.EtcPath, cfgBase), l)\n\t\t\tif err != nil {\n\t\t\t\tl.Error().Str(\"name\", name).Err(err).Msg(initErrMsg)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcollectors = append(collectors, c)\n\n\t\tcase NameFS:\n\t\t\tc, err := NewFSCollector(path.Join(defaults.EtcPath, cfgBase), l)\n\t\t\tif err != nil {\n\t\t\t\tl.Error().Str(\"name\", name).Err(err).Msg(initErrMsg)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcollectors = append(collectors, c)\n\n\t\tcase NameLoad:\n\t\t\tc, err := NewLoadCollector(path.Join(defaults.EtcPath, cfgBase), l)\n\t\t\tif err != nil {\n\t\t\t\tl.Error().Str(\"name\", name).Err(err).Msg(initErrMsg)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcollectors = append(collectors, c)\n\n\t\tcase NameIF:\n\t\t\tc, err := NewNetIFCollector(path.Join(defaults.EtcPath, cfgBase), l)\n\t\t\tif err != nil {\n\t\t\t\tl.Error().Str(\"name\", name).Err(err).Msg(initErrMsg)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcollectors = append(collectors, c)\n\n\t\tcase NameProto:\n\t\t\tc, err := NewNetProtoCollector(path.Join(defaults.EtcPath, cfgBase), l)\n\t\t\tif err != nil {\n\t\t\t\tl.Error().Str(\"name\", name).Err(err).Msg(initErrMsg)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcollectors = append(collectors, c)\n\n\t\tcase NameVM:\n\t\t\tc, err := NewVMCollector(path.Join(defaults.EtcPath, cfgBase), l)\n\t\t\tif err != nil {\n\t\t\t\tl.Error().Str(\"name\", name).Err(err).Msg(initErrMsg)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcollectors = append(collectors, c)\n\n\t\tdefault:\n\t\t\tl.Warn().Str(\"name\", name).Msg(\"unknown builtin collector, ignoring\")\n\t\t}\n\t}\n\n\treturn collectors, nil\n}", "func NewResourceCollector() Collector {\n\treturn &ResourceCollector{}\n}", "func runMockCollector(t *testing.T) *mockCollector {\n\tt.Helper()\n\treturn runMockCollectorAtEndpoint(t, \"localhost:0\")\n}", "func NewCollector(m Metric) (prometheus.Collector, error) {\n\tif len(m.Name) == 0 {\n\t\treturn nil, errors.New(\"A name is required for a metric\")\n\t}\n\n\tvar (\n\t\tnamespace = m.Namespace\n\t\tsubsystem = m.Subsystem\n\t\thelp = m.Help\n\t)\n\n\tif len(namespace) == 0 {\n\t\tnamespace = DefaultNamespace\n\t}\n\n\tif len(subsystem) == 0 {\n\t\tsubsystem = DefaultSubsystem\n\t}\n\n\tif len(help) == 0 {\n\t\thelp = m.Name\n\t}\n\n\tswitch m.Type {\n\tcase CounterType:\n\t\treturn prometheus.NewCounterVec(prometheus.CounterOpts{\n\t\t\tNamespace: namespace,\n\t\t\tSubsystem: subsystem,\n\t\t\tName: m.Name,\n\t\t\tHelp: help,\n\t\t\tConstLabels: prometheus.Labels(m.ConstLabels),\n\t\t}, m.LabelNames), nil\n\n\tcase GaugeType:\n\t\treturn prometheus.NewGaugeVec(prometheus.GaugeOpts{\n\t\t\tNamespace: namespace,\n\t\t\tSubsystem: subsystem,\n\t\t\tName: m.Name,\n\t\t\tHelp: help,\n\t\t\tConstLabels: prometheus.Labels(m.ConstLabels),\n\t\t}, m.LabelNames), nil\n\n\tcase HistogramType:\n\t\treturn prometheus.NewHistogramVec(prometheus.HistogramOpts{\n\t\t\tNamespace: namespace,\n\t\t\tSubsystem: subsystem,\n\t\t\tName: m.Name,\n\t\t\tHelp: help,\n\t\t\tBuckets: m.Buckets,\n\t\t\tConstLabels: prometheus.Labels(m.ConstLabels),\n\t\t}, m.LabelNames), nil\n\n\tcase SummaryType:\n\t\treturn prometheus.NewSummaryVec(prometheus.SummaryOpts{\n\t\t\tNamespace: namespace,\n\t\t\tSubsystem: subsystem,\n\t\t\tName: m.Name,\n\t\t\tHelp: help,\n\t\t\tObjectives: m.Objectives,\n\t\t\tMaxAge: m.MaxAge,\n\t\t\tAgeBuckets: m.AgeBuckets,\n\t\t\tBufCap: m.BufCap,\n\t\t\tConstLabels: prometheus.Labels(m.ConstLabels),\n\t\t}, m.LabelNames), nil\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unsupported metric type: %s\", m.Type)\n\t}\n}" ]
[ "0.6678328", "0.6632261", "0.65414196", "0.6530185", "0.6512622", "0.64971226", "0.6375079", "0.63555616", "0.62438387", "0.6209447", "0.62021196", "0.6182788", "0.61450464", "0.61132157", "0.6028201", "0.5957508", "0.5919775", "0.59160614", "0.5884967", "0.584295", "0.5818363", "0.5813408", "0.5796612", "0.57958037", "0.57937145", "0.5763175", "0.57328385", "0.57328385", "0.5729203", "0.56940603", "0.5681324", "0.562854", "0.5611518", "0.5608728", "0.5590831", "0.55822337", "0.5556737", "0.55410874", "0.55182654", "0.5514137", "0.54964495", "0.5458126", "0.5452869", "0.5449635", "0.5426785", "0.54175997", "0.5395875", "0.5351163", "0.53433245", "0.532839", "0.53127676", "0.52667826", "0.5228756", "0.5219424", "0.52175856", "0.5157324", "0.5149614", "0.5131001", "0.51267165", "0.51158744", "0.50946003", "0.5080261", "0.5072781", "0.50422317", "0.5025364", "0.50229204", "0.5018788", "0.5005706", "0.50038433", "0.50032115", "0.50030875", "0.50000304", "0.49936917", "0.49897853", "0.49752948", "0.4953986", "0.4935506", "0.4928988", "0.49287137", "0.492823", "0.492333", "0.4909444", "0.49048173", "0.48751152", "0.487385", "0.4856579", "0.48553073", "0.48511878", "0.48499566", "0.48474383", "0.48390934", "0.48356548", "0.4813391", "0.48126405", "0.48084393", "0.4806013", "0.48043263", "0.48022977", "0.4794451", "0.4787403" ]
0.7760482
0
NewTLSRemoteCollector creates a RemoteCollector that uses TLS.
NewTLSRemoteCollector создает RemoteCollector, который использует TLS.
func NewTLSRemoteCollector(addr string, tlsConfig *tls.Config) *RemoteCollector { return &RemoteCollector{ addr: addr, dial: func() (net.Conn, error) { return tls.Dial("tcp", addr, tlsConfig) }, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewTLSConnection(\n\tsrvRemote Remote,\n\trootCerts []byte,\n\terrorUnwrapper ErrorUnwrapper,\n\thandler ConnectionHandler,\n\tlogFactory LogFactory,\n\tinstrumenterStorage NetworkInstrumenterStorage,\n\tlogOutput LogOutputWithDepthAdder,\n\tmaxFrameLength int32,\n\topts ConnectionOpts,\n) *Connection {\n\ttransport := &ConnectionTransportTLS{\n\t\trootCerts: rootCerts,\n\t\tsrvRemote: srvRemote,\n\t\tmaxFrameLength: maxFrameLength,\n\t\tlogFactory: logFactory,\n\t\tinstrumenterStorage: instrumenterStorage,\n\t\twef: opts.WrapErrorFunc,\n\t\tdialerTimeout: opts.DialerTimeout,\n\t\thandshakeTimeout: opts.HandshakeTimeout,\n\t\tlog: newConnectionLogUnstructured(logOutput, \"CONNTSPT\"),\n\t}\n\treturn newConnectionWithTransportAndProtocols(handler, transport, errorUnwrapper, logOutput, opts)\n}", "func NewTTLSListener(laddr string, x509Opts *X509Opts) (*TTLS, error) {\n\tt := TTLS{\n\t\tx509Opts: x509Opts,\n\t}\n\tconfig, err := t.getConfig()\n\tif err != nil {\n\t\treturn &t, err\n\t}\n\tlistener, err := tls.Listen(\"tcp\", laddr, config)\n\tif err != nil {\n\t\treturn &t, err\n\t}\n\tt.Listener = listener\n\treturn &t, nil\n}", "func newTLSConfig(target string, registry *prometheus.Registry, cfg *config.TLSConfig) (*tls.Config, error) {\n\ttlsConfig, err := config.NewTLSConfig(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif tlsConfig.ServerName == \"\" && target != \"\" {\n\t\ttargetAddress, _, err := net.SplitHostPort(target)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttlsConfig.ServerName = targetAddress\n\t}\n\n\ttlsConfig.VerifyConnection = func(state tls.ConnectionState) error {\n\t\treturn collectConnectionStateMetrics(state, registry)\n\t}\n\n\treturn tlsConfig, nil\n}", "func NewRemoteCollector(addr string) *RemoteCollector {\n\treturn &RemoteCollector{\n\t\taddr: addr,\n\t\tdial: func() (net.Conn, error) {\n\t\t\treturn net.Dial(\"tcp\", addr)\n\t\t},\n\t}\n}", "func NewServerTLS(addr string,\n\thandler func(conn Conn, cmd Command),\n\taccept func(conn Conn) bool,\n\tclosed func(conn Conn, err error),\n\tconfig *tls.Config,\n) *TLSServer {\n\treturn NewServerNetworkTLS(\"tcp\", addr, handler, accept, closed, config)\n}", "func GenerateTLS(hosts string, validity string) (*CertificateChain, error) {\n\treturn tls.GenerateTLS(hosts, validity)\n}", "func NewTLS(c Config, t *tls.Config) (*Asock, error) {\n\tl, err := tls.Listen(\"tcp\", c.Sockname, t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn commonNew(c, l), nil\n}", "func NewTLSConnectionWithTLSConfig(\n\tsrvRemote Remote,\n\ttlsConfig *tls.Config,\n\terrorUnwrapper ErrorUnwrapper,\n\thandler ConnectionHandler,\n\tlogFactory LogFactory,\n\tinstrumenterStorage NetworkInstrumenterStorage,\n\tlogOutput LogOutputWithDepthAdder,\n\tmaxFrameLength int32,\n\topts ConnectionOpts,\n) *Connection {\n\ttransport := &ConnectionTransportTLS{\n\t\tsrvRemote: srvRemote,\n\t\ttlsConfig: copyTLSConfig(tlsConfig),\n\t\tmaxFrameLength: maxFrameLength,\n\t\tlogFactory: logFactory,\n\t\tinstrumenterStorage: instrumenterStorage,\n\t\twef: opts.WrapErrorFunc,\n\t\tdialerTimeout: opts.DialerTimeout,\n\t\thandshakeTimeout: opts.HandshakeTimeout,\n\t\tlog: newConnectionLogUnstructured(logOutput, \"CONNTSPT\"),\n\t}\n\treturn newConnectionWithTransportAndProtocols(handler, transport, errorUnwrapper, logOutput, opts)\n}", "func NewListenerTLS(network, addr, certFile, keyFile string, readTimeout, writeTimeout time.Duration) (net.Listener, error) {\n\tconfig := &tls.Config{}\n\tif config.NextProtos == nil {\n\t\tconfig.NextProtos = []string{\"http/1.1\"}\n\t}\n\n\tvar err error\n\tconfig.Certificates = make([]tls.Certificate, 1)\n\tconfig.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconn, err := net.Listen(network, addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttl := &Listener{\n\t\tListener: tls.NewListener(conn, config),\n\t\tReadTimeout: readTimeout,\n\t\tWriteTimeout: writeTimeout,\n\t}\n\treturn tl, nil\n}", "func NewTLSConn() TLSConn {\n\tc := TLSConn{}\n\n\tc.tlsVersions = []uint16{\n\t\ttls.VersionSSL30,\n\t\ttls.VersionTLS10,\n\t\ttls.VersionTLS11,\n\t\ttls.VersionTLS12,\n\t\ttls.VersionTLS13,\n\t}\n\n\tc.tlsCurves = []tls.CurveID{\n\t\ttls.CurveP256,\n\t\ttls.CurveP384,\n\t\ttls.CurveP521,\n\t\ttls.X25519,\n\t}\n\n\tc.conf = &tls.Config{}\n\n\treturn c\n}", "func NewTLSServer(cfg TLSServerConfig) (*TLSServer, error) {\n\tif err := cfg.CheckAndSetDefaults(); err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\t// limiter limits requests by frequency and amount of simultaneous\n\t// connections per client\n\tlimiter, err := limiter.NewLimiter(cfg.LimiterConfig)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\t// sets up gRPC metrics interceptor\n\tgrpcMetrics := metrics.CreateGRPCServerMetrics(cfg.Metrics.GRPCServerLatency, prometheus.Labels{teleport.TagServer: \"teleport-auth\"})\n\terr = metrics.RegisterPrometheusCollectors(grpcMetrics)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tlocalClusterName, err := cfg.AccessPoint.GetClusterName()\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\t// authMiddleware authenticates request assuming TLS client authentication\n\t// adds authentication information to the context\n\t// and passes it to the API server\n\tauthMiddleware := &Middleware{\n\t\tClusterName: localClusterName.GetClusterName(),\n\t\tAcceptedUsage: cfg.AcceptedUsage,\n\t\tLimiter: limiter,\n\t\tGRPCMetrics: grpcMetrics,\n\t}\n\n\tapiServer, err := NewAPIServer(&cfg.APIConfig)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tauthMiddleware.Wrap(apiServer)\n\t// Wrap sets the next middleware in chain to the authMiddleware\n\tlimiter.WrapHandle(authMiddleware)\n\t// force client auth if given\n\tcfg.TLS.ClientAuth = tls.VerifyClientCertIfGiven\n\tcfg.TLS.NextProtos = []string{http2.NextProtoTLS}\n\n\tsecurityHeaderHandler := httplib.MakeSecurityHeaderHandler(limiter)\n\ttracingHandler := httplib.MakeTracingHandler(securityHeaderHandler, teleport.ComponentAuth)\n\n\tserver := &TLSServer{\n\t\tcfg: cfg,\n\t\thttpServer: &http.Server{\n\t\t\tHandler: tracingHandler,\n\t\t\tReadTimeout: apidefaults.DefaultIOTimeout,\n\t\t\tReadHeaderTimeout: defaults.ReadHeadersTimeout,\n\t\t\tWriteTimeout: apidefaults.DefaultIOTimeout,\n\t\t\tIdleTimeout: apidefaults.DefaultIdleTimeout,\n\t\t},\n\t\tlog: logrus.WithFields(logrus.Fields{\n\t\t\ttrace.Component: cfg.Component,\n\t\t}),\n\t}\n\tserver.cfg.TLS.GetConfigForClient = server.GetConfigForClient\n\n\tserver.grpcServer, err = NewGRPCServer(GRPCServerConfig{\n\t\tTLS: server.cfg.TLS,\n\t\tMiddleware: authMiddleware,\n\t\tAPIConfig: cfg.APIConfig,\n\t\tUnaryInterceptors: authMiddleware.UnaryInterceptors(),\n\t\tStreamInterceptors: authMiddleware.StreamInterceptors(),\n\t})\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tserver.mux, err = multiplexer.NewTLSListener(multiplexer.TLSListenerConfig{\n\t\tListener: tls.NewListener(cfg.Listener, server.cfg.TLS),\n\t\tID: cfg.ID,\n\t})\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tif cfg.PluginRegistry != nil {\n\t\tif err := cfg.PluginRegistry.RegisterAuthServices(server.grpcServer); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t}\n\n\treturn server, nil\n}", "func NewTLSConfig() *tls.Config {\n\treturn &tls.Config{\n\t\tInsecureSkipVerify: false,\n\t\tMinVersion: tls.VersionTLS12,\n\t}\n}", "func newTLSServer(handler http.Handler) *httptest.Server {\n\tts := httptest.NewUnstartedServer(handler)\n\tts.TLS = new(tls.Config)\n\tts.TLS.NextProtos = []string{\"h2\"}\n\tts.StartTLS()\n\treturn ts\n}", "func TestNewConfigTLS(t *testing.T) {\n\tconfig, err := NewConfig(\"configs/tls.yaml\")\n\trequire.NoError(t, err)\n\t// Liftbridge TLS\n\trequire.Equal(t, \"./configs/certs/server/server-key.pem\", config.TLSKey)\n\trequire.Equal(t, \"./configs/certs/server/server-cert.pem\", config.TLSCert)\n}", "func NewServerNetworkTLS(\n\tnet, laddr string,\n\thandler func(conn Conn, cmd Command),\n\taccept func(conn Conn) bool,\n\tclosed func(conn Conn, err error),\n\tconfig *tls.Config,\n) *TLSServer {\n\tif handler == nil {\n\t\tpanic(\"handler is nil\")\n\t}\n\ts := Server{\n\t\tnet: net,\n\t\tladdr: laddr,\n\t\thandler: handler,\n\t\taccept: accept,\n\t\tclosed: closed,\n\t\tconns: make(map[*conn]bool),\n\t}\n\n\ttls := &TLSServer{\n\t\tconfig: config,\n\t\tServer: &s,\n\t}\n\treturn tls\n}", "func newTLSRoutingTunnelDialer(ssh ssh.ClientConfig, keepAlivePeriod, dialTimeout time.Duration, discoveryAddr string, insecure bool) ContextDialer {\n\treturn ContextDialerFunc(func(ctx context.Context, network, addr string) (conn net.Conn, err error) {\n\t\tresp, err := webclient.Find(&webclient.Config{Context: ctx, ProxyAddr: discoveryAddr, Insecure: insecure})\n\t\tif err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\n\t\tif !resp.Proxy.TLSRoutingEnabled {\n\t\t\treturn nil, trace.NotImplemented(\"TLS routing is not enabled\")\n\t\t}\n\n\t\ttunnelAddr, err := resp.Proxy.TunnelAddr()\n\t\tif err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\n\t\tdialer := &net.Dialer{\n\t\t\tTimeout: dialTimeout,\n\t\t\tKeepAlive: keepAlivePeriod,\n\t\t}\n\t\tconn, err = dialer.DialContext(ctx, network, tunnelAddr)\n\t\tif err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\n\t\thost, _, err := webclient.ParseHostPort(tunnelAddr)\n\t\tif err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\n\t\ttlsConn := tls.Client(conn, &tls.Config{\n\t\t\tNextProtos: []string{constants.ALPNSNIProtocolReverseTunnel},\n\t\t\tInsecureSkipVerify: insecure,\n\t\t\tServerName: host,\n\t\t})\n\t\tif err := tlsConn.Handshake(); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\n\t\tsconn, err := sshConnect(ctx, tlsConn, ssh, dialTimeout, tunnelAddr)\n\t\tif err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\n\t\treturn sconn, nil\n\t})\n}", "func NewTlsConfig(t *Tls, extra ...PeerVerifier) (*tls.Config, error) {\n\tif t == nil {\n\t\treturn nil, nil\n\t}\n\n\tif len(t.CertificateFile) == 0 || len(t.KeyFile) == 0 {\n\t\treturn nil, ErrTlsCertificateRequired\n\t}\n\n\tvar nextProtos []string\n\tif len(t.NextProtos) > 0 {\n\t\tnextProtos = append(nextProtos, t.NextProtos...)\n\t} else {\n\t\t// assume http/1.1 by default\n\t\tnextProtos = append(nextProtos, \"http/1.1\")\n\t}\n\n\ttc := &tls.Config{ // nolint: gosec\n\t\tMinVersion: t.MinVersion,\n\t\tMaxVersion: t.MaxVersion,\n\t\tServerName: t.ServerName,\n\t\tNextProtos: nextProtos,\n\n\t\t// disable vulnerable ciphers\n\t\tCipherSuites: []uint16{\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,\n\t\t},\n\t}\n\n\t// if no MinVersion was set, default to TLS 1.2\n\tif tc.MinVersion == 0 {\n\t\ttc.MinVersion = tls.VersionTLS12\n\t}\n\n\tif pvs := NewPeerVerifiers(t.PeerVerify, extra...); len(pvs) > 0 {\n\t\ttc.VerifyPeerCertificate = pvs.VerifyPeerCertificate\n\t}\n\n\tif cert, err := tls.LoadX509KeyPair(t.CertificateFile, t.KeyFile); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\ttc.Certificates = []tls.Certificate{cert}\n\t}\n\n\tif len(t.ClientCACertificateFile) > 0 {\n\t\tcaCert, err := os.ReadFile(t.ClientCACertificateFile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tcaCertPool := x509.NewCertPool()\n\t\tif !caCertPool.AppendCertsFromPEM(caCert) {\n\t\t\treturn nil, ErrUnableToAddClientCACertificate\n\t\t}\n\n\t\ttc.ClientCAs = caCertPool\n\t\ttc.ClientAuth = tls.RequireAndVerifyClientCert\n\t}\n\n\ttc.BuildNameToCertificate() // nolint: staticcheck\n\treturn tc, nil\n}", "func NewTLSConnectionWithConnectionLogFactory(\n\tsrvRemote Remote,\n\trootCerts []byte,\n\terrorUnwrapper ErrorUnwrapper,\n\thandler ConnectionHandler,\n\tlogFactory LogFactory,\n\tinstrumenterStorage NetworkInstrumenterStorage,\n\tconnectionLogFactory ConnectionLogFactory,\n\tmaxFrameLength int32,\n\topts ConnectionOpts,\n) *Connection {\n\ttransport := &ConnectionTransportTLS{\n\t\trootCerts: rootCerts,\n\t\tsrvRemote: srvRemote,\n\t\tmaxFrameLength: maxFrameLength,\n\t\tinstrumenterStorage: instrumenterStorage,\n\t\tlogFactory: logFactory,\n\t\twef: opts.WrapErrorFunc,\n\t\tdialerTimeout: opts.DialerTimeout,\n\t\thandshakeTimeout: opts.HandshakeTimeout,\n\t\tlog: connectionLogFactory.Make(\"conn_tspt\"),\n\t}\n\tconnLog := connectionLogFactory.Make(\"conn\")\n\treturn newConnectionWithTransportAndProtocolsWithLog(\n\t\thandler, transport, errorUnwrapper, connLog, opts)\n}", "func NewLocalRouterCollector(ctx context.Context, logger *slog.Logger, errors *prometheus.CounterVec, client platform.LocalRouterClient) *LocalRouterCollector {\n\terrors.WithLabelValues(\"local_router\").Add(0)\n\n\tlocalRouterLabels := []string{\"id\", \"name\"}\n\tlocalRouterInfoLabels := append(localRouterLabels, \"tags\", \"description\")\n\tlocalRouterSwitchInfoLabels := append(localRouterLabels, \"category\", \"code\", \"zone_id\")\n\tlocalRouterServerNetworkInfoLabels := append(localRouterLabels, \"vip\", \"ipaddress1\", \"ipaddress2\", \"nw_mask_len\", \"vrid\")\n\tlocalRouterPeerLabels := append(localRouterLabels, \"peer_index\", \"peer_id\")\n\tlocalRouterPeerInfoLabels := append(localRouterPeerLabels, \"enabled\", \"description\")\n\tlocalRouterStaticRouteInfoLabels := append(localRouterLabels, \"route_index\", \"prefix\", \"next_hop\")\n\n\treturn &LocalRouterCollector{\n\t\tctx: ctx,\n\t\tlogger: logger,\n\t\terrors: errors,\n\t\tclient: client,\n\t\tUp: prometheus.NewDesc(\n\t\t\t\"sakuracloud_local_router_up\",\n\t\t\t\"If 1 the LocalRouter is available, 0 otherwise\",\n\t\t\tlocalRouterLabels, nil,\n\t\t),\n\t\tLocalRouterInfo: prometheus.NewDesc(\n\t\t\t\"sakuracloud_local_router_info\",\n\t\t\t\"A metric with a constant '1' value labeled by localRouter information\",\n\t\t\tlocalRouterInfoLabels, nil,\n\t\t),\n\t\tSwitchInfo: prometheus.NewDesc(\n\t\t\t\"sakuracloud_local_router_switch_info\",\n\t\t\t\"A metric with a constant '1' value labeled by localRouter connected switch information\",\n\t\t\tlocalRouterSwitchInfoLabels, nil,\n\t\t),\n\t\tNetworkInfo: prometheus.NewDesc(\n\t\t\t\"sakuracloud_local_router_network_info\",\n\t\t\t\"A metric with a constant '1' value labeled by network information of the localRouter\",\n\t\t\tlocalRouterServerNetworkInfoLabels, nil,\n\t\t),\n\t\tPeerInfo: prometheus.NewDesc(\n\t\t\t\"sakuracloud_local_router_peer_info\",\n\t\t\t\"A metric with a constant '1' value labeled by peer information\",\n\t\t\tlocalRouterPeerInfoLabels, nil,\n\t\t),\n\t\tPeerUp: prometheus.NewDesc(\n\t\t\t\"sakuracloud_local_router_peer_up\",\n\t\t\t\"If 1 the Peer is available, 0 otherwise\",\n\t\t\tlocalRouterPeerLabels, nil,\n\t\t),\n\t\tStaticRouteInfo: prometheus.NewDesc(\n\t\t\t\"sakuracloud_local_router_static_route_info\",\n\t\t\t\"A metric with a constant '1' value labeled by static route information\",\n\t\t\tlocalRouterStaticRouteInfoLabels, nil,\n\t\t),\n\t\tReceiveBytesPerSec: prometheus.NewDesc(\n\t\t\t\"sakuracloud_local_router_receive_per_sec\",\n\t\t\t\"Receive bytes per seconds\",\n\t\t\tlocalRouterLabels, nil,\n\t\t),\n\t\tSendBytesPerSec: prometheus.NewDesc(\n\t\t\t\"sakuracloud_local_router_send_per_sec\",\n\t\t\t\"Send bytes per seconds\",\n\t\t\tlocalRouterLabels, nil,\n\t\t),\n\t}\n}", "func (in *TLS) DeepCopy() *TLS {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(TLS)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *TLS) DeepCopy() *TLS {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(TLS)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func newServerTLSConfig(certPEM, keyPEM, caPEM []byte) (*tls.Config, error) {\n\tcfg, err := newBaseTLSConfig(certPEM, keyPEM, caPEM)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcfg.ClientAuth = tls.VerifyClientCertIfGiven\n\tcfg.ClientCAs = cfg.RootCAs\n\t// Use the default cipher suite from golang (RC4 is going away in 1.5).\n\t// Prefer the server-specified suite.\n\tcfg.PreferServerCipherSuites = true\n\t// Should we disable session resumption? This may break forward secrecy.\n\t// cfg.SessionTicketsDisabled = true\n\treturn cfg, nil\n}", "func NewTLSServer(vfs vfs.FileSystem) *Server {\n\tts := NewUnstartedServer(vfs)\n\tts.StartTLS()\n\treturn ts\n}", "func NewCollector(rcClientId string, kubernetesClusterId string) TelemetryCollector {\n\treturn &telemetryCollector{\n\t\tclient: httputils.NewResetClient(httpClientResetInterval, httpClientFactory(httpClientTimeout)),\n\t\thost: utils.GetMainEndpoint(config.Datadog, mainEndpointPrefix, mainEndpointUrlKey),\n\t\tuserAgent: \"Datadog Cluster Agent\",\n\t\trcClientId: rcClientId,\n\t\tkubernetesClusterId: kubernetesClusterId,\n\t}\n}", "func NewHTTPCollector(url string, options ...HTTPOption) (Collector, error) {\n\tc := &HTTPCollector{\n\t\tlogger: NewNopLogger(),\n\t\turl: url,\n\t\tclient: &http.Client{Timeout: defaultHTTPTimeout},\n\t\tbatchInterval: defaultHTTPBatchInterval * time.Second,\n\t\tbatchSize: defaultHTTPBatchSize,\n\t\tbatch: []*zipkincore.Span{},\n\t\tspanc: make(chan *zipkincore.Span, defaultHTTPBatchSize),\n\t\tquit: make(chan struct{}, 1),\n\t\tshutdown: make(chan error, 1),\n\t\tbatchPool: sync.Pool{\n\t\t\tNew: func() interface{} {\n\t\t\t\treturn make([]*zipkincore.Span, 0, defaultHTTPBatchSize)\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, option := range options {\n\t\toption(c)\n\t}\n\n\tgo c.loop()\n\treturn c, nil\n}", "func NewCollector(period time.Duration, collectFunc func() []Measurement) *Collector {\n\tcollector := &Collector{\n\t\tperiod: period,\n\t\tcollectFunc: collectFunc,\n\t\tlastSendingDate: -1,\n\t}\n\n\tif sources == nil {\n\t\tsources = make([]DataSource, 0)\n\t\tgo sendingLoop()\n\t}\n\n\tif UseGlobalEngine {\n\t\tcollector.Engine = Engine\n\t} else {\n\t\tcollector.Engine = &req.Engine{}\n\t}\n\n\tsources = append(sources, collector)\n\n\treturn collector\n}", "func NewCollector(username string, token string, source string, timeout time.Duration, waitGroup *sync.WaitGroup) Collector {\n\treturn &collector{\n\t\turl: metricsEndpont,\n\t\tusername: username,\n\t\ttoken: token,\n\t\tsource: source,\n\t\ttimeout: timeout,\n\n\t\thttpClient: &http.Client{\n\t\t\tTimeout: time.Second * 30,\n\t\t},\n\t\twaitGroup: waitGroup,\n\t\tstop: make(chan bool),\n\t\tbuffer: make(chan gauge, 10000),\n\t}\n}", "func TLS(v *tls.Config) Configer {\n\treturn func(c *clientv3.Config) {\n\t\tc.TLS = v\n\t}\n}", "func NewRemote(ctx context.Context, conn *grpc.ClientConn) Subjects {\n\treturn &remote{\n\t\tclient: NewServiceClient(conn),\n\t}\n}", "func newRemoteClusterHTTPTransport() *http.Transport {\n\ttr := &http.Transport{\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tTLSClientConfig: &tls.Config{\n\t\t\tRootCAs: globalRootCAs,\n\t\t},\n\t}\n\treturn tr\n}", "func newTLSCACertPool(useSystemCertPool bool) *exampleTLSCACertPool {\n\tm := &exampleTLSCACertPool{}\n\tvar err error\n\tm.tlsCertPool, err = commtls.NewCertPool(useSystemCertPool)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn m\n}", "func NewCollector(store *store.MemoryStore) *Collector {\n\treturn &Collector{\n\t\tstore: store,\n\t\tstopChan: make(chan struct{}),\n\t\tdoneChan: make(chan struct{}),\n\t}\n}", "func createTlsConfig() {\n\n}", "func NewCollector(cfg *config.AgentConfig) TelemetryCollector {\n\tif !cfg.TelemetryConfig.Enabled {\n\t\treturn &noopTelemetryCollector{}\n\t}\n\n\tvar endpoints []config.Endpoint\n\tfor _, endpoint := range cfg.TelemetryConfig.Endpoints {\n\t\tu, err := url.Parse(endpoint.Host)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tu.Path = \"/api/v2/apmtelemetry\"\n\t\tendpointWithPath := *endpoint\n\t\tendpointWithPath.Host = u.String()\n\n\t\tendpoints = append(endpoints, endpointWithPath)\n\t}\n\n\treturn &telemetryCollector{\n\t\tclient: cfg.NewHTTPClient(),\n\t\tendpoints: endpoints,\n\t\tuserAgent: fmt.Sprintf(\"Datadog Trace Agent/%s/%s\", cfg.AgentVersion, cfg.GitCommit),\n\n\t\tcfg: cfg,\n\t\tcollectedStartupError: &atomic.Bool{},\n\t}\n}", "func (socket *SocketTLS) New(name string, port string, tlsCert string, tlsKey string) (chan SocketEvent, error) {\n\tvar err error\n\n\tsocket.name = name\n\tsocket.port = port\n\tsocket.eventChan = make(chan SocketEvent, 1000)\n\n\t// Listen for incoming connections.\n\tcer, err := tls.LoadX509KeyPair(tlsCert, tlsKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconfig := &tls.Config{\n\t\tCertificates: []tls.Certificate{cer},\n\t\tClientAuth: tls.NoClientCert,\n\t\tMinVersion: tls.VersionSSL30,\n\t\tInsecureSkipVerify: true,\n\t\t//MaxVersion: tls.VersionSSL30,\n\t\tCipherSuites: []uint16{\n\t\t\ttls.TLS_RSA_WITH_RC4_128_SHA,\n\t\t},\n\t}\n\tsocket.listen, err = tls.Listen(\"tcp\", \"0.0.0.0:\"+socket.port, config)\n\n\tif err != nil {\n\t\tlog.Errorf(\"%s: Listening on 0.0.0.0:%s threw an error.\\n%v\", socket.name, socket.port, err)\n\t\treturn nil, err\n\t}\n\tlog.Noteln(socket.name + \": Listening on 0.0.0.0:\" + socket.port)\n\n\t// Accept new connections in a new Goroutine(\"thread\")\n\tgo socket.run()\n\n\treturn socket.eventChan, nil\n}", "func newOptionalTlsCreds() *optionalTlsCreds {\n\treturn &optionalTlsCreds{\n\t\ttlsForPort: make(map[string]credentials.TransportCredentials),\n\t}\n}", "func newTLSSecret(vr *api.VaultService, caKey *rsa.PrivateKey, caCrt *x509.Certificate, commonName, secretName string,\n\taddrs []string, fieldMap map[string]string) (*v1.Secret, error) {\n\ttc := tls.CertConfig{\n\t\tCommonName: commonName,\n\t\tOrganization: orgForTLSCert,\n\t\tAltNames: tls.NewAltNames(addrs),\n\t}\n\tkey, crt, err := newKeyAndCert(caCrt, caKey, tc)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"new TLS secret failed: %v\", err)\n\t}\n\tsecret := &v1.Secret{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"Secret\",\n\t\t\tAPIVersion: \"v1\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: secretName,\n\t\t\tNamespace: vr.Namespace,\n\t\t\tLabels: labelsForVault(vr.Name),\n\t\t},\n\t\tData: map[string][]byte{\n\t\t\tfieldMap[\"key\"]: tls.EncodePrivateKeyPEM(key),\n\t\t\tfieldMap[\"cert\"]: tls.EncodeCertificatePEM(crt),\n\t\t\tfieldMap[\"ca\"]: tls.EncodeCertificatePEM(caCrt),\n\t\t},\n\t}\n\treturn secret, nil\n}", "func NewTLSConnectionWithDialable(\n\tsrvRemote Remote,\n\trootCerts []byte,\n\terrorUnwrapper ErrorUnwrapper,\n\thandler ConnectionHandler,\n\tlogFactory LogFactory,\n\tinstrumenterStorage NetworkInstrumenterStorage,\n\tlogOutput LogOutputWithDepthAdder,\n\tmaxFrameLength int32,\n\topts ConnectionOpts,\n\tdialable Dialable,\n) *Connection {\n\ttransport := &ConnectionTransportTLS{\n\t\trootCerts: rootCerts,\n\t\tsrvRemote: srvRemote,\n\t\tmaxFrameLength: maxFrameLength,\n\t\tlogFactory: logFactory,\n\t\tinstrumenterStorage: instrumenterStorage,\n\t\twef: opts.WrapErrorFunc,\n\t\tdialerTimeout: opts.DialerTimeout,\n\t\thandshakeTimeout: opts.HandshakeTimeout,\n\t\tlog: newConnectionLogUnstructured(logOutput, \"CONNTSPT\"),\n\t\tdialable: dialable,\n\t}\n\treturn newConnectionWithTransportAndProtocols(handler, transport, errorUnwrapper, logOutput, opts)\n}", "func newTLSCredentials(\n\tmountPath string,\n\tkey corev1.SecretKeySelector,\n\tcert monitoringv1.SecretOrConfigMap,\n\tclientCA monitoringv1.SecretOrConfigMap,\n) *tlsCredentials {\n\treturn &tlsCredentials{\n\t\tmountPath: mountPath,\n\t\tkeySecret: key,\n\t\tcert: cert,\n\t\tclientCA: clientCA,\n\t}\n}", "func DialTLS(tlsConfig *tls.Config) (*Conn, error) {\n\treturn DialToTLS(\"\", tlsConfig)\n}", "func NewSSLTransport(ctx context.Context, addr string, config *tls.Config) (*TCPTransport, error) {\n\tdialer := tls.Dialer{\n\t\tNetDialer: &net.Dialer{},\n\t\tConfig: config,\n\t}\n\tconn, err := dialer.DialContext(ctx, \"tcp\", addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttcp := &TCPTransport{\n\t\tconn: conn,\n\t\tresponses: make(chan []byte),\n\t\terrors: make(chan error),\n\t}\n\n\tgo tcp.listen()\n\n\treturn tcp, nil\n}", "func NewKubeletCerts() workflow.Phase {\n\treturn workflow.Phase{\n\t\tName: \"kubelet-certs\",\n\t\tShort: \"Kubelet certificate generation\",\n\t\tPhases: []workflow.Phase{\n\t\t\t{\n\t\t\t\tName: \"all\",\n\t\t\t\tShort: \"Prepares kubelet server certificates\",\n\t\t\t},\n\t\t},\n\t\tRun: runCerts,\n\t\tLong: cmdutil.MacroCommandLongDescription,\n\t}\n}", "func NewTLSTransport(config TLSConfig, inner Transport) (*TLSTransport, error) {\n\ttransport := &TLSTransport{inner: inner}\n\ttc := &transport.tlsConfig\n\n\tcert, err := tls.LoadX509KeyPair(config.Cert, config.Key)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to load key pair\")\n\t}\n\ttc.Certificates = append(tc.Certificates, cert)\n\n\tif len(config.CAs) == 0 {\n\t\tif runtime.GOOS == \"windows\" {\n\t\t\tif len(config.ExtraCAs) > 0 {\n\t\t\t\treturn nil, errors.New(\n\t\t\t\t\t\"currently adding extra CA(s) to \" +\n\t\t\t\t\t\t\"system default CA pool is not supported on Windows\")\n\t\t\t}\n\t\t} else {\n\t\t\tif tc.RootCAs, err = x509.SystemCertPool(); err != nil {\n\t\t\t\treturn nil, errors.Wrap(err, \"failed to load system CA pool\")\n\t\t\t}\n\t\t}\n\t} else {\n\t\ttc.RootCAs = x509.NewCertPool()\n\t}\n\tcaToAdd := append(config.CAs, config.ExtraCAs...)\n\tfor i := range caToAdd {\n\t\tif err := addCA(tc.RootCAs, caToAdd[i]); err != nil {\n\t\t\treturn nil, errors.Wrapf(\n\t\t\t\terr, \"failed to add %s to the root ca list\", caToAdd[i])\n\t\t}\n\t}\n\n\tif config.VerifyClient {\n\t\ttc.ClientAuth = tls.RequireAndVerifyClientCert\n\t}\n\n\tif len(config.ClientCAs) > 0 {\n\t\ttc.ClientCAs = x509.NewCertPool()\n\t\tfor i := range config.ClientCAs {\n\t\t\tif err := addCA(tc.ClientCAs, config.ClientCAs[i]); err != nil {\n\t\t\t\treturn nil, errors.Wrapf(err,\n\t\t\t\t\t\"failed to add %s to the client ca list\",\n\t\t\t\t\tconfig.ClientCAs[i])\n\t\t\t}\n\t\t}\n\t}\n\n\ttc.MinVersion = tls.VersionTLS11\n\n\ttc.CipherSuites = []uint16{\n\t\ttls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,\n\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,\n\t\ttls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,\n\t\ttls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,\n\t\ttls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,\n\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,\n\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,\n\t\ttls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,\n\t}\n\n\ttc.ClientSessionCache = tls.NewLRUClientSessionCache(\n\t\tconfig.SessionCacheSize)\n\n\tif config.HandshakeTimeout != \"\" {\n\t\tt, err := time.ParseDuration(config.HandshakeTimeout)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"invalid handshake_timeout\")\n\t\t}\n\t\tif t <= 0 {\n\t\t\treturn nil, errors.New(\"handshake_timeout should be > 0\")\n\t\t}\n\t\ttransport.handshakeTimeout = t\n\t} else {\n\t\ttransport.handshakeTimeout = defaultTLSHandshakeTimeout\n\t}\n\n\treturn transport, nil\n}", "func newEtcdServerTLSSecret(vr *api.VaultService, caKey *rsa.PrivateKey, caCrt *x509.Certificate) (*v1.Secret, error) {\n\treturn newTLSSecret(vr, caKey, caCrt, \"etcd server\", etcdServerTLSSecretName(vr.Name),\n\t\t[]string{\n\t\t\t\"localhost\",\n\t\t\tfmt.Sprintf(\"*.%s.%s.svc\", etcdNameForVault(vr.Name), vr.Namespace),\n\t\t\tfmt.Sprintf(\"%s-client\", etcdNameForVault(vr.Name)),\n\t\t\tfmt.Sprintf(\"%s-client.%s\", etcdNameForVault(vr.Name), vr.Namespace),\n\t\t\tfmt.Sprintf(\"%s-client.%s.svc\", etcdNameForVault(vr.Name), vr.Namespace),\n\t\t\tfmt.Sprintf(\"*.%s.%s.svc.%s\", etcdNameForVault(vr.Name), vr.Namespace, defaultClusterDomain),\n\t\t\tfmt.Sprintf(\"%s-client.%s.svc.%s\", etcdNameForVault(vr.Name), vr.Namespace, defaultClusterDomain),\n\t\t},\n\t\tmap[string]string{\n\t\t\t\"key\": \"server.key\",\n\t\t\t\"cert\": \"server.crt\",\n\t\t\t\"ca\": \"server-ca.crt\",\n\t\t})\n}", "func ServeTLS(l net.Listener, handler Handler, certFile, keyFile string) error {\n\tsrv := &Server{Handler: handler}\n\treturn srv.ServeTLS(l, certFile, keyFile)\n}", "func NewCollector(l *logrus.Entry, updateInterval time.Duration) *Collector {\n\tcol := &Collector{\n\t\tMsgEvtChan: make(chan *discordgo.Message, 1000),\n\t\tinterval: updateInterval,\n\t\tl: l,\n\t\tchannels: make(map[int64]*entry),\n\t}\n\n\tgo col.run()\n\n\treturn col\n}", "func NewServerTLSConfig(certs []tls.Certificate, rootCAPool *x509.CertPool) (*tls.Config, error) {\n\tif rootCAPool == nil {\n\t\treturn nil, errors.New(\"valid root CA pool required\")\n\t}\n\n\treturn &tls.Config{\n\t\tCertificates: certs,\n\t\t// Since we're using the same CA server to issue Certificates to new nodes, we can't\n\t\t// use tls.RequireAndVerifyClientCert\n\t\tClientAuth: tls.VerifyClientCertIfGiven,\n\t\tRootCAs: rootCAPool,\n\t\tClientCAs: rootCAPool,\n\t\tPreferServerCipherSuites: true,\n\t\tMinVersion: tls.VersionTLS12,\n\t}, nil\n}", "func NewServer(l net.Listener, c Collector) *CollectorServer {\n\tcs := &CollectorServer{c: c, l: l}\n\treturn cs\n}", "func NewTLSStateMachine() State {\n\tnormal := &Normal{}\n\tauthedstream := &AuthedStream{Next: normal}\n\tauthedstart := &AuthedStart{Next: authedstream}\n\ttlsauth := &TLSAuth{Next: authedstart}\n\ttlsstartstream := &TLSStartStream{Next: tlsauth}\n\ttlsupgrade := &TLSUpgrade{Next: tlsstartstream}\n\tfirststream := &TLSUpgradeRequest{Next: tlsupgrade}\n\tstart := &Start{Next: firststream}\n\treturn start\n}", "func NewTlsInspectionPolicy(ctx *pulumi.Context,\n\tname string, args *TlsInspectionPolicyArgs, opts ...pulumi.ResourceOption) (*TlsInspectionPolicy, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.CaPool == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'CaPool'\")\n\t}\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource TlsInspectionPolicy\n\terr := ctx.RegisterResource(\"gcp:networksecurity/tlsInspectionPolicy:TlsInspectionPolicy\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (c *Client) InitTLS(certFile string) error {\n\tserverCert, err := ioutil.ReadFile(certFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tCA_Pool := x509.NewCertPool()\n\tCA_Pool.AppendCertsFromPEM(serverCert)\n\tc.mutex.Lock()\n\tc.rootCAs = CA_Pool\n\tc.mutex.Unlock()\n\tif c.agentProvider != nil {\n\t\treturn c.agentProvider.Refresh()\n\t}\n\treturn nil\n}", "func NewDNSOverTLS(dial DialContextFunc, address string) DNSOverTCP {\n\treturn DNSOverTCP{\n\t\tdial: dial,\n\t\taddress: address,\n\t\tnetwork: \"dot\",\n\t\trequiresPadding: true,\n\t}\n}", "func NewTlsCipherPolicy(ctx *pulumi.Context,\n\tname string, args *TlsCipherPolicyArgs, opts ...pulumi.ResourceOption) (*TlsCipherPolicy, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.Ciphers == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Ciphers'\")\n\t}\n\tif args.TlsCipherPolicyName == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'TlsCipherPolicyName'\")\n\t}\n\tif args.TlsVersions == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'TlsVersions'\")\n\t}\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource TlsCipherPolicy\n\terr := ctx.RegisterResource(\"alicloud:slb/tlsCipherPolicy:TlsCipherPolicy\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func NewTLSHandshakerUTLS(logger model.DebugLogger, id *utls.ClientHelloID) model.TLSHandshaker {\n\treturn newTLSHandshaker(&tlsHandshakerConfigurable{\n\t\tNewConn: newUTLSConnFactory(id),\n\t}, logger)\n}", "func newVaultServerTLSSecret(vr *api.VaultService, caKey *rsa.PrivateKey, caCrt *x509.Certificate) (*v1.Secret, error) {\n\treturn newTLSSecret(vr, caKey, caCrt, \"vault server\", api.DefaultVaultServerTLSSecretName(vr.Name),\n\t\t[]string{\n\t\t\t\"localhost\",\n\t\t\tfmt.Sprintf(\"*.%s.pod\", vr.Namespace),\n\t\t\tfmt.Sprintf(\"%s.%s.svc\", vr.Name, vr.Namespace),\n\t\t},\n\t\tmap[string]string{\n\t\t\t\"key\": \"server.key\",\n\t\t\t\"cert\": \"server.crt\",\n\t\t\t// The CA is not used by the server\n\t\t\t\"ca\": \"server-ca.crt\",\n\t\t})\n}", "func NewCollector(config *Config) (coll *Collector, err error) {\n\tvar gelfWriter *gelf.Writer\n\n\tif gelfWriter, err = gelf.NewWriter(config.Graylog.Address); err != nil {\n\t\treturn nil, err\n\t}\n\n\tcoll = new(Collector)\n\tcoll.writer = gelfWriter\n\tcoll.host = config.Collector.Hostname\n\n\treturn coll, nil\n}", "func NewCollector(bindIP, port string) (*SyslogCollector, error) {\n\tdefer TRA(CE())\n\tchannel := make(syslog.LogPartsChannel)\n\tsysServ := syslog.NewServer()\n\tsysServ.SetHandler(syslog.NewChannelHandler(channel))\n\t// uses RFC3164 because it is default for rsyslog\n\tsysServ.SetFormat(syslog.RFC3164)\n\terr := sysServ.ListenUDP(fmt.Sprintf(\"%s:%s\", bindIP, port))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgo func(channel syslog.LogPartsChannel) {\n\t\tfor logEntry := range channel {\n\t\t\tinfo, err := ctl.NewHostInfo()\n\t\t\tif err != nil {\n\t\t\t\tinfo = &ctl.HostInfo{}\n\t\t\t}\n\t\t\tevent, err := ctl.NewEvent(logEntry, *info)\n\t\t\tif err != nil {\n\t\t\t\tErrorLogger.Printf(\"cannot format syslog entry: %s\\n\", err)\n\t\t\t}\n\t\t\terr = event.Save(SubmitPath())\n\t\t\tif err != nil {\n\t\t\t\tErrorLogger.Printf(\"cannot save syslog entry to file: %s\\n\", err)\n\t\t\t}\n\t\t}\n\t}(channel)\n\treturn &SyslogCollector{\n\t\tserver: sysServ,\n\t\tport: port,\n\t}, nil\n}", "func NewServerTLSConfig(caCrtFile, certFile, keyFile string) (*tls.Config, error) {\n\ttc := &tls.Config{}\n\n\tpool := x509.NewCertPool()\n\tcaCertPath := caCrtFile\n\n\tcaCrt, err := ioutil.ReadFile(caCertPath)\n\tif err != nil {\n\t\tfmt.Println(\"ReadFile err:\", err)\n\t\treturn nil, err\n\t}\n\tpool.AppendCertsFromPEM(caCrt)\n\n\ttc.ClientCAs = pool\n\n\tif certFile != \"\" {\n\t\tcliCrt, err := tls.LoadX509KeyPair(certFile, keyFile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttc.Certificates = []tls.Certificate{cliCrt}\n\t}\n\treturn tc, nil\n}", "func NewCollector(logicalSystem string) collector.RPCCollector {\n\treturn &bgpCollector{LogicalSystem: logicalSystem}\n}", "func NewListenerWithKeepAliveTLS(l net.Listener, tlsConfig *tls.Config) net.Listener {\n\tln := &listenerWithKeepAliveTLS{}\n\tln.Listener = l\n\tln.tlsConfig = tlsConfig\n\treturn ln\n}", "func (aps *ApiServer) RunTLS() error {\n\treturn aps.Engine.RunTLS(aps.ipAddr+\":\"+strconv.Itoa(aps.port), aps.certFile, aps.keyFile)\n}", "func TLSGenServer(c agent.Config, options ...tlsx.Option) (creds *tls.Config, err error) {\n\tvar (\n\t\tpool *x509.CertPool\n\t)\n\n\tif err = os.MkdirAll(c.CredentialsDir, 0700); err != nil {\n\t\treturn creds, errors.WithStack(err)\n\t}\n\n\tif pool, err = x509.SystemCertPool(); err != nil {\n\t\treturn creds, errors.WithStack(err)\n\t}\n\n\tm := NewDirectory(\n\t\tc.ServerName,\n\t\tc.CredentialsDir,\n\t\tc.CA,\n\t\tpool,\n\t)\n\n\tcreds = &tls.Config{\n\t\tServerName: c.ServerName,\n\t\tClientAuth: tls.RequireAndVerifyClientCert,\n\t\tGetCertificate: m.GetCertificate,\n\t\tGetClientCertificate: m.GetClientCertificate,\n\t\tClientCAs: pool,\n\t\tRootCAs: pool,\n\t\tNextProtos: []string{\"bw.mux\"},\n\t}\n\n\treturn tlsx.Clone(creds, options...)\n}", "func (m *cMux) ServeTLS(l net.Listener, tLSConfig *tls.Config, certFile, keyFile string) error {\n\tconfig := cloneTLSConfig(tLSConfig)\n\tif !strings.SliceContains(config.NextProtos, \"http/1.1\") {\n\t\tconfig.NextProtos = append(config.NextProtos, \"http/1.1\")\n\t}\n\n\tconfigHasCert := len(config.Certificates) > 0 || config.GetCertificate != nil\n\tif !configHasCert || certFile != \"\" || keyFile != \"\" {\n\t\tvar err error\n\t\tconfig.Certificates = make([]tls.Certificate, 1)\n\t\tconfig.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttlsListener := tls.NewListener(l, config)\n\treturn m.Serve(tlsListener)\n}", "func (instance *TLSProvider) CreateListener(network string, address string) (listener net.Listener, err error) {\n\tconfig := &tls.Config{\n\t\tClientAuth: tls.NoClientCert,\n\t\t//MinVersion: tls.VersionTLS10,\n\t\tNextProtos: []string{\"h2\", \"http/1.1\"},\n\t\tGetCertificate: instance.GetCertificate,\n\t\tPreferServerCipherSuites: true,\n\t\t// If CipherSuites is nil, a default list of secure cipher suites is used, with a preference order based on hardware performance.\n\t\t/*\n\t\t\tCipherSuites: []uint16{\n\t\t\t\t// https://pkg.go.dev/crypto/tls#pkg-constants\n\n\t\t\t\t// TLS 1.0 - 1.2 (for RSA server certifacte)\n\t\t\t\t//tls.TLS_RSA_WITH_RC4_128_SHA, // 142.03 req/s\n\t\t\t\t//tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA, // 27.58 req/s\n\t\t\t\t//tls.TLS_RSA_WITH_AES_128_CBC_SHA, // 168.58 req/s\n\t\t\t\t//tls.TLS_RSA_WITH_AES_256_CBC_SHA, // 164.96 req/s\n\t\t\t\t//tls.TLS_RSA_WITH_AES_128_CBC_SHA256, // 128.54 req/s\n\t\t\t\t//tls.TLS_RSA_WITH_AES_128_GCM_SHA256, // 221.98 req/s\n\t\t\t\t//tls.TLS_RSA_WITH_AES_256_GCM_SHA384, // 214.77 req/s\n\t\t\t\t//tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA, // ? req/s\n\t\t\t\t//tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, // ? req/s\n\t\t\t\t//tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, // ? req/s\n\t\t\t\t//tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, // ? req/s\n\t\t\t\t//tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, // ? req/s\n\t\t\t\t//tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, // 189.06 req/s\n\t\t\t\t//tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, // 183.72 req/s\n\t\t\t\t//tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, // 130.55 req/s\n\t\t\t\t// TLS 1.0 - 1.2 (for ECC server certificate)\n\t\t\t\t//tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, // ? req/s\n\t\t\t\t//tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, // ? req/s\n\t\t\t\t//tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, // ? req/s\n\t\t\t\t//tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, // ? req/s\n\t\t\t\t//tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, // ? req/s\n\t\t\t\t//tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, // ? req/s\n\t\t\t\t//tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, // ? req/s\n\t\t\t\t// TLS 1.3\n\t\t\t\t//tls.TLS_AES_128_GCM_SHA256, // ? req/s\n\t\t\t\t//tls.TLS_AES_256_GCM_SHA384, // ? req/s\n\t\t\t\t//tls.TLS_CHACHA20_POLY1305_SHA256, // ? req/s\n\t\t\t},\n\t\t*/\n\t}\n\tlistener, err = net.Listen(network, address)\n\tif err != nil {\n\t\treturn\n\t}\n\tlistener = tls.NewListener(listener, config)\n\treturn\n}", "func ConfigTLS(c Config) *tls.Config {\n\tsCert, err := tls.LoadX509KeyPair(c.CertFile, c.KeyFile)\n\tif err != nil {\n\t\tglog.Fatal(err)\n\t}\n\treturn &tls.Config{\n\t\tCertificates: []tls.Certificate{sCert},\n\t\t// TODO: uses mutual tls after we agree on what cert the apiserver should use.\n\t\t// ClientAuth: tls.RequireAndVerifyClientCert,\n\t}\n}", "func NewCollector(cfg *config.AgentConfig, ctx context.Context) (Collector, error) {\n\tsysInfo, err := checks.CollectSystemInfo(cfg)\n\tif err != nil {\n\t\treturn Collector{}, err\n\t}\n\n\tenabledChecks := make([]checks.Check, 0)\n\tfor _, c := range checks.All {\n\t\tif cfg.CheckIsEnabled(c.Name()) {\n\t\t\tc.Init(cfg, sysInfo)\n\t\t\tenabledChecks = append(enabledChecks, c)\n\t\t}\n\t}\n\n\treturn NewCollectorWithChecks(cfg, enabledChecks, ctx), nil\n}", "func NewRTCDtlsTransport(transport *RTCIceTransport, certificates []RTCCertificate) (*RTCDtlsTransport, error) {\n\tt := &RTCDtlsTransport{iceTransport: transport}\n\n\tif len(certificates) > 0 {\n\t\tnow := time.Now()\n\t\tfor _, x509Cert := range certificates {\n\t\t\tif !x509Cert.Expires().IsZero() && now.After(x509Cert.Expires()) {\n\t\t\t\treturn nil, &rtcerr.InvalidAccessError{Err: ErrCertificateExpired}\n\t\t\t}\n\t\t\tt.certificates = append(t.certificates, x509Cert)\n\t\t}\n\t} else {\n\t\tsk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)\n\t\tif err != nil {\n\t\t\treturn nil, &rtcerr.UnknownError{Err: err}\n\t\t}\n\t\tcertificate, err := GenerateCertificate(sk)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tt.certificates = []RTCCertificate{*certificate}\n\t}\n\n\treturn t, nil\n}", "func NewTLSKey(tlsKeyPath, tlsCertPath string) error {\n\tpriv, err := rsa.GenerateKey(rand.Reader, 4096)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnotBefore := time.Now()\n\tnotAfter := notBefore.Add(certificateDuration)\n\tserialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)\n\tserialNumber, err := rand.Int(rand.Reader, serialNumberLimit)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttemplate := x509.Certificate{\n\t\tSerialNumber: serialNumber,\n\t\tNotBefore: notBefore,\n\t\tNotAfter: notAfter,\n\t\tKeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,\n\t\tExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},\n\t\tBasicConstraintsValid: true,\n\t}\n\tderBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcertOut, err := os.Create(tlsCertPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer certOut.Close() // nolint: errcheck\n\tif err = pem.Encode(certOut, &pem.Block{Type: \"CERTIFICATE\", Bytes: derBytes}); err != nil {\n\t\treturn err\n\t}\n\n\tkeyOut, err := os.OpenFile(tlsKeyPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer keyOut.Close() // nolint: errcheck\n\terr = pem.Encode(keyOut, &pem.Block{\n\t\tType: \"RSA PRIVATE KEY\",\n\t\tBytes: x509.MarshalPKCS1PrivateKey(priv),\n\t})\n\treturn err\n}", "func (i *MonitorInstance) setTLSConfig(ctx context.Context, enableTLS bool, configs map[string]any, paths meta.DirPaths) (map[string]any, error) {\n\treturn nil, nil\n}", "func NewLocalCollector(s Store) Collector {\n\treturn s\n}", "func NewVaultCollector() (Collector, error) {\n\taddr := os.Getenv(\"VAULT_ADDR\")\n\tcaCert := os.Getenv(\"VAULT_CACERT\")\n\tcaPath := os.Getenv(\"VAULT_CAPATH\")\n\tserverName := \"\"\n\tif addr != \"\" {\n\t\turl, err := url.Parse(addr)\n\t\tif err != nil {\n\t\t\treturn nil, maskAny(err)\n\t\t}\n\t\thost, _, err := net.SplitHostPort(url.Host)\n\t\tif err != nil {\n\t\t\treturn nil, maskAny(err)\n\t\t}\n\t\tserverName = host\n\t}\n\tvar certPool *x509.CertPool\n\tif caCert != \"\" || caPath != \"\" {\n\t\tvar err error\n\t\tif caCert != \"\" {\n\t\t\tlog.Debugf(\"Loading CA cert: %s\", caCert)\n\t\t\tcertPool, err = LoadCACert(caCert)\n\t\t} else {\n\t\t\tlog.Debugf(\"Loading CA certs from: %s\", caPath)\n\t\t\tcertPool, err = LoadCAPath(caPath)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, maskAny(err)\n\t\t}\n\t}\n\n\ttransport := cleanhttp.DefaultTransport()\n\ttransport.Proxy = nil\n\ttransport.TLSClientConfig = &tls.Config{\n\t\tServerName: serverName,\n\t\tRootCAs: certPool,\n\t\t//InsecureSkipVerify: true,\n\t}\n\tclient := &http.Client{\n\t\tTransport: transport,\n\t}\n\tc := &vaultCollector{\n\t\taddress: addr,\n\t\tclient: client,\n\t\tvaultUnsealedDesc: prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(vaultNamespace, \"\", \"server_unsealed\"),\n\t\t\t\"Vault unseal status (1=unsealed, 0=sealed)\", []string{\"address\"}, nil,\n\t\t),\n\t\tstatus: make(map[string]float64),\n\t}\n\tgo c.updateStatusLoop()\n\treturn c, nil\n}", "func NewHTTPS(host string, port int) Static {\n\treturn Static{\n\t\tprotocol: ProtocolHTTPS,\n\t\thost: host,\n\t\tport: port,\n\t}\n}", "func upgradeTLS(c *v1Conn, line string, hooks EventHooks) (err error) {\n\tif c.tlsConfig == nil {\n\t\terr = c.printfLine(\"%s TLS not supported\", RPL_TLSRejected)\n\t} else {\n\t\terr = c.printfLine(\"%s Continue with TLS Negotiation\", RPL_TLSContinue)\n\t\tif err == nil {\n\t\t\ttconn := tls.Server(c.conn, c.tlsConfig)\n\t\t\terr = tconn.Handshake()\n\t\t\tif err == nil {\n\t\t\t\t// successful tls handshake\n\t\t\t\tc.tlsConn = tconn\n\t\t\t\tc.C = textproto.NewConn(c.tlsConn)\n\t\t\t} else {\n\t\t\t\t// tls failed\n\t\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\t\"pkg\": \"nntp-conn\",\n\t\t\t\t\t\"addr\": c.conn.RemoteAddr(),\n\t\t\t\t\t\"state\": c.state,\n\t\t\t\t}).Warn(\"TLS Handshake failed \", err)\n\t\t\t\t// fall back to plaintext\n\t\t\t\terr = nil\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func New(chainID, remote string) (provider.Provider, error) {\n\thttpClient, err := rpcclient.NewHTTP(remote, \"/websocket\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewWithClient(chainID, httpClient), nil\n}", "func WithTLS(certs []tls.Certificate) Option {\n\treturn func(g *GRPC) {\n\t\tg.certs = certs\n\t}\n}", "func NewTLSField(name string) *ConfigField {\n\ttf := btls.FieldSpec()\n\ttf.Name = name\n\ttf.Type = docs.FieldTypeObject\n\tvar newChildren []docs.FieldSpec\n\tfor _, f := range tf.Children {\n\t\tif f.Name != \"enabled\" {\n\t\t\tnewChildren = append(newChildren, f)\n\t\t}\n\t}\n\ttf.Children = newChildren\n\treturn &ConfigField{field: tf}\n}", "func (c Control) ServeTLS(w http.ResponseWriter, r *http.Request) {\n\ttemplate := map[string]interface{}{}\n\tc.Config.RLock()\n\ttls, err := json.Marshal(c.Config.TLS)\n\tc.Config.RUnlock()\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t} else {\n\t\ttemplate[\"tls\"] = string(tls)\n\t\tserveTemplate(w, r, \"tls\", template)\n\t}\n}", "func New(subjectNames ...string) *tls.Config {\n\tif len(subjectNames) == 0 {\n\t\tsubjectNames = []string{\"localhost\"}\n\t}\n\tssconfig := SelfSignedConfig{\n\t\tSAN: subjectNames,\n\t\tKeyType: RSA4096,\n\t\tExpire: time.Now().Add(10 * time.Hour * 24 * 365),\n\t}\n\tcert, _ := newSelfSignedCertificate(ssconfig)\n\treturn &tls.Config{Certificates: []tls.Certificate{cert}}\n}", "func newTunnel(nc *nats.Conn, subject string, readTimeout time.Duration, respHandler func(response *Response)) *Tunnel {\n\treturn &Tunnel{\n\t\tsubject: subject,\n\t\tnc: nc,\n\t\tdone: make(chan bool),\n\t\trespHandler: respHandler,\n\t\trandSuffix: &RandomSuffix{\n\t\t\trandomGenerator: rand.New(rand.NewSource(time.Now().UnixNano())), //nolint gosec\n\t\t},\n\t\tmon: tunnelMon{\n\t\t\treadTimeout: readTimeout,\n\t\t},\n\t}\n}", "func NewCollector() collector.RPCCollector {\n\treturn &vpwsCollector{}\n}", "func (in *ListenerTLS) DeepCopy() *ListenerTLS {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ListenerTLS)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func NewTLSKey(tlsKeyPath, tlsCertPath string, keySize int) error {\n\tpriv, template, err := generateTLSTemplate(nil, keySize)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Self-signed certificate: template == parent\n\tderBytes, err := x509.CreateCertificate(rand.Reader, template, template, &priv.PublicKey, priv)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = writeCertificate(tlsCertPath, derBytes); err != nil {\n\t\treturn err\n\t}\n\treturn writePrivateKey(tlsKeyPath, priv)\n}", "func NewStatsCollector(cliContext *cli.Context) (*StatsCollector, error) {\n\n\t// fill the Collector struct\n\tcollector := &StatsCollector{\n\t\tcliContext: cliContext,\n\t\tsocketPath: cliContext.String(\"socketPath\"),\n\t\tkamailioHost: cliContext.String(\"host\"),\n\t\tkamailioPort: cliContext.Int(\"port\"),\n\t}\n\n\t// fine, return the created object struct\n\treturn collector, nil\n}", "func TelemetryHarvesterWithTLSConfig(tlsConfig *tls.Config) TelemetryHarvesterOpt {\n\n\treturn func(cfg *telemetry.Config) {\n\t\trt := cfg.Client.Transport\n\t\tif rt == nil {\n\t\t\trt = http.DefaultTransport\n\t\t}\n\n\t\tt, ok := rt.(*http.Transport)\n\t\tif !ok {\n\t\t\tlogrus.Warning(\n\t\t\t\t\"telemetry emitter TLS configuration couldn't be set, \",\n\t\t\t\t\"client transport is not an http.Transport.\",\n\t\t\t)\n\t\t\treturn\n\t\t}\n\n\t\tt = t.Clone()\n\t\tt.TLSClientConfig = tlsConfig\n\t\tcfg.Client.Transport = http.RoundTripper(t)\n\t\treturn\n\t}\n}", "func newUTLSConnFactory(clientHello *utls.ClientHelloID) func(conn net.Conn, config *tls.Config) (TLSConn, error) {\n\treturn func(conn net.Conn, config *tls.Config) (TLSConn, error) {\n\t\treturn NewUTLSConn(conn, config, clientHello)\n\t}\n}", "func NewDialerWithTLSConfig(opts *DialerOptions, tls *tls.Config) *Dialer {\n\treturn &Dialer{opts: opts, tls: tls}\n}", "func NewSinker(rcm cm.RemoteConfManager) *Sinker {\n\tctx, cancel := context.WithCancel(context.Background())\n\ts := &Sinker{\n\t\ttasks: make(map[string]*task.Service),\n\t\trcm: rcm,\n\t\tctx: ctx,\n\t\tcancel: cancel,\n\t\tstopped: make(chan struct{}),\n\t}\n\treturn s\n}", "func NewCmdCreateSecretTLS(f cmdutil.Factory, cmdOut io.Writer) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"tls NAME --cert=path/to/cert/file --key=path/to/key/file [--dry-run]\",\n\t\tShort: i18n.T(\"Create a TLS secret\"),\n\t\tLong: secretForTLSLong,\n\t\tExample: secretForTLSExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\terr := CreateSecretTLS(f, cmdOut, cmd, args)\n\t\t\tcmdutil.CheckErr(err)\n\t\t},\n\t}\n\tcmdutil.AddApplyAnnotationFlags(cmd)\n\tcmdutil.AddValidateFlags(cmd)\n\tcmdutil.AddPrinterFlags(cmd)\n\tcmdutil.AddGeneratorFlags(cmd, cmdutil.SecretForTLSV1GeneratorName)\n\tcmd.Flags().String(\"cert\", \"\", i18n.T(\"Path to PEM encoded public key certificate.\"))\n\tcmd.Flags().String(\"key\", \"\", i18n.T(\"Path to private key associated with given certificate.\"))\n\treturn cmd\n}", "func NewAuth(bufnet *bufconn.Listener, certs *trust.Provider, pool trust.ProviderPool) (remote *RemotePeer, err error) {\n\tif bufnet == nil {\n\t\tbufnet = bufconn.New()\n\t}\n\n\tvar creds grpc.ServerOption\n\tif creds, err = mtls.ServerCreds(certs, pool); err != nil {\n\t\treturn nil, err\n\t}\n\n\tremote = &RemotePeer{\n\t\tbufnet: bufnet,\n\t\tsrv: grpc.NewServer(creds),\n\t\tCalls: make(map[string]int),\n\t}\n\n\tapi.RegisterTRISANetworkServer(remote.srv, remote)\n\tapi.RegisterTRISAHealthServer(remote.srv, remote)\n\tgo remote.srv.Serve(remote.bufnet.Sock())\n\treturn remote, nil\n}", "func (c *Client) DialTLS(ctx context.Context, target string, file string, name string, opts ...grpc.DialOption) (conn *grpc.ClientConn, err error) {\n\tvar creds credentials.TransportCredentials\n\tcreds, err = credentials.NewClientTLSFromFile(file, name)\n\tif err != nil {\n\t\terr = errors.WithStack(err)\n\t\treturn\n\t}\n\topts = append(opts, grpc.WithTransportCredentials(creds))\n\treturn c.dial(ctx, target, opts...)\n}", "func newServer(cert *shared.CertInfo, handler http.Handler) *httptest.Server {\n\tserver := httptest.NewUnstartedServer(handler)\n\tserver.TLS = util.ServerTLSConfig(cert)\n\tserver.StartTLS()\n\treturn server\n}", "func (s *Server) generateTLSConfig(opts *TLSOptions) (*tls.Config, error) {\n\treturn generateTLSConfig(opts)\n}", "func New(cfg smtpcf.SMTP, tlsConfig *tls.Config) (SMTP, error) {\n\tif tlsConfig == nil {\n\t\t/* #nosec */\n\t\t//nolint #nosec\n\t\ttlsConfig = &tls.Config{}\n\t}\n\n\tif cfg == nil {\n\t\treturn nil, ErrorParamEmpty.Error(nil)\n\t} else {\n\t\treturn &smtpClient{\n\t\t\tmut: sync.Mutex{},\n\t\t\tcfg: cfg,\n\t\t\ttls: tlsConfig,\n\t\t}, nil\n\t}\n}", "func NewListener(inner net.Listener, config *tls.Config,) net.Listener", "func MQTTNewTLSConfig(crtPath, keyPath string, skipVerify bool) (*tls.Config, error) {\n\t// Import trusted certificates from CAfile.pem.\n\t// Alternatively, manually add CA certificates to\n\t// default openssl CA bundle.\n\tcertpool := x509.NewCertPool()\n\tpemCerts, err := ioutil.ReadFile(\"samplecerts/CAfile.pem\")\n\tif err == nil {\n\t\tcertpool.AppendCertsFromPEM(pemCerts)\n\t}\n\n\t// Import client certificate/key pair\n\tcert, err := tls.LoadX509KeyPair(crtPath, keyPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create tls.Config with desired tls properties\n\treturn &tls.Config{\n\t\t// RootCAs = certs used to verify server cert.\n\t\tRootCAs: certpool,\n\t\t// ClientAuth = whether to request cert from server.\n\t\t// Since the server is set up for SSL, this happens\n\t\t// anyways.\n\t\tClientAuth: tls.NoClientCert,\n\t\t// ClientCAs = certs used to validate client cert.\n\t\tClientCAs: nil,\n\t\t// InsecureSkipVerify = verify that cert contents\n\t\t// match server. IP matches what is in cert etc.\n\t\tInsecureSkipVerify: skipVerify,\n\t\t// Certificates = list of certs client sends to server.\n\t\tCertificates: []tls.Certificate{cert},\n\t}, nil\n}", "func WithTLS(cfg *tls.Config) DialerOption {\n\treturn func(d *dialer) {\n\t\td.tlsConfig = cfg\n\t}\n}", "func newTLSConfig(clientCert, clientKey, caCert string) (*tls.Config, error) {\n\tvalid := false\n\n\tconfig := &tls.Config{}\n\n\tif clientCert != \"\" && clientKey != \"\" {\n\t\tcert, err := tls.X509KeyPair([]byte(clientCert), []byte(clientKey))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tconfig.Certificates = []tls.Certificate{cert}\n\t\tconfig.BuildNameToCertificate()\n\t\tvalid = true\n\t}\n\n\tif caCert != \"\" {\n\t\tcaCertPool := x509.NewCertPool()\n\t\tcaCertPool.AppendCertsFromPEM([]byte(caCert))\n\t\tconfig.RootCAs = caCertPool\n\t\t// The CN of Heroku Kafka certs do not match the hostname of the\n\t\t// broker, but Go's default TLS behavior requires that they do.\n\t\tconfig.VerifyPeerCertificate = verifyCertSkipHostname(caCertPool)\n\t\tconfig.InsecureSkipVerify = true\n\t\tvalid = true\n\t}\n\n\tif !valid {\n\t\tconfig = nil\n\t}\n\n\treturn config, nil\n}", "func newTLSConfig(clientCert, clientKey, caCert string) (*tls.Config, error) {\n\tvalid := false\n\n\tconfig := &tls.Config{}\n\n\tif clientCert != \"\" && clientKey != \"\" {\n\t\tcert, err := tls.X509KeyPair([]byte(clientCert), []byte(clientKey))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tconfig.Certificates = []tls.Certificate{cert}\n\t\tconfig.BuildNameToCertificate()\n\t\tvalid = true\n\t}\n\n\tif caCert != \"\" {\n\t\tcaCertPool := x509.NewCertPool()\n\t\tcaCertPool.AppendCertsFromPEM([]byte(caCert))\n\t\tconfig.RootCAs = caCertPool\n\t\t// The CN of Heroku Kafka certs do not match the hostname of the\n\t\t// broker, but Go's default TLS behavior requires that they do.\n\t\tconfig.VerifyPeerCertificate = verifyCertSkipHostname(caCertPool)\n\t\tconfig.InsecureSkipVerify = true\n\t\tvalid = true\n\t}\n\n\tif !valid {\n\t\tconfig = nil\n\t}\n\n\treturn config, nil\n}", "func New(opts Options) (*Transport, error) {\n\tswitch {\n\tcase opts.ServerCfg.ServerURI == \"\":\n\t\treturn nil, errors.New(\"missing server URI when creating a new transport\")\n\tcase opts.ServerCfg.CredsDialOption() == nil:\n\t\treturn nil, errors.New(\"missing credentials when creating a new transport\")\n\tcase opts.OnRecvHandler == nil:\n\t\treturn nil, errors.New(\"missing OnRecv callback handler when creating a new transport\")\n\tcase opts.OnErrorHandler == nil:\n\t\treturn nil, errors.New(\"missing OnError callback handler when creating a new transport\")\n\tcase opts.OnSendHandler == nil:\n\t\treturn nil, errors.New(\"missing OnSend callback handler when creating a new transport\")\n\t}\n\n\t// Dial the xDS management with the passed in credentials.\n\tdopts := []grpc.DialOption{\n\t\topts.ServerCfg.CredsDialOption(),\n\t\tgrpc.WithKeepaliveParams(keepalive.ClientParameters{\n\t\t\t// We decided to use these sane defaults in all languages, and\n\t\t\t// kicked the can down the road as far making these configurable.\n\t\t\tTime: 5 * time.Minute,\n\t\t\tTimeout: 20 * time.Second,\n\t\t}),\n\t}\n\tcc, err := grpcDial(opts.ServerCfg.ServerURI, dopts...)\n\tif err != nil {\n\t\t// An error from a non-blocking dial indicates something serious.\n\t\treturn nil, fmt.Errorf(\"failed to create a transport to the management server %q: %v\", opts.ServerCfg.ServerURI, err)\n\t}\n\n\tboff := opts.Backoff\n\tif boff == nil {\n\t\tboff = backoff.DefaultExponential.Backoff\n\t}\n\tret := &Transport{\n\t\tcc: cc,\n\t\tserverURI: opts.ServerCfg.ServerURI,\n\t\tonRecvHandler: opts.OnRecvHandler,\n\t\tonErrorHandler: opts.OnErrorHandler,\n\t\tonSendHandler: opts.OnSendHandler,\n\t\tlrsStore: load.NewStore(),\n\t\tbackoff: boff,\n\t\tnodeProto: opts.NodeProto,\n\t\tlogger: opts.Logger,\n\n\t\tadsStreamCh: make(chan adsStream, 1),\n\t\tadsRequestCh: buffer.NewUnbounded(),\n\t\tresources: make(map[string]map[string]bool),\n\t\tversions: make(map[string]string),\n\t\tnonces: make(map[string]string),\n\t\tadsRunnerDoneCh: make(chan struct{}),\n\t}\n\n\t// This context is used for sending and receiving RPC requests and\n\t// responses. It is also used by all the goroutines spawned by this\n\t// Transport. Therefore, cancelling this context when the transport is\n\t// closed will essentially cancel any pending RPCs, and cause the goroutines\n\t// to terminate.\n\tctx, cancel := context.WithCancel(context.Background())\n\tret.adsRunnerCancel = cancel\n\tgo ret.adsRunner(ctx)\n\n\tret.logger.Infof(\"Created transport to server %q\", ret.serverURI)\n\treturn ret, nil\n}", "func newDefaultTLSConfig(cert *tls.Certificate) (*tls.Config, error) {\n\ttlsConfig := &tls.Config{\n\t\tMinVersion: tls.VersionTLS12,\n\t\t// Prioritize cipher suites sped up by AES-NI (AES-GCM)\n\t\tCipherSuites: []uint16{\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,\n\t\t},\n\t\tPreferServerCipherSuites: true,\n\t\t// Use curves which have assembly implementations\n\t\tCurvePreferences: []tls.CurveID{\n\t\t\ttls.CurveP256,\n\t\t\ttls.X25519,\n\t\t},\n\t\tCertificates: []tls.Certificate{*cert},\n\t\t// HTTP/2 must be enabled manually when using http.Serve\n\t\tNextProtos: []string{\"h2\"},\n\t}\n\ttlsConfig.BuildNameToCertificate()\n\treturn tlsConfig, nil\n}" ]
[ "0.62902963", "0.616452", "0.6161178", "0.58453023", "0.58117586", "0.5769236", "0.5683554", "0.5679266", "0.5537916", "0.5532538", "0.5434783", "0.5386184", "0.53491753", "0.53105533", "0.53019303", "0.5281855", "0.5261915", "0.5235258", "0.52274466", "0.52274024", "0.52274024", "0.5205211", "0.5201315", "0.5158286", "0.5151248", "0.5135499", "0.5133801", "0.5122583", "0.5095577", "0.5085333", "0.50828254", "0.50801593", "0.50666016", "0.5053201", "0.5033838", "0.5024432", "0.50233066", "0.5017911", "0.50106347", "0.5005666", "0.4993772", "0.49708512", "0.49609303", "0.49428183", "0.49413005", "0.4939193", "0.49371424", "0.49369955", "0.49331027", "0.49309513", "0.49226564", "0.49165308", "0.4911474", "0.4910168", "0.49100795", "0.48936152", "0.4893379", "0.48841503", "0.48833552", "0.48793432", "0.48759323", "0.48753542", "0.4872549", "0.48718435", "0.4869328", "0.48674065", "0.48665768", "0.48635638", "0.4851744", "0.48254755", "0.4822707", "0.48202437", "0.48189571", "0.4817854", "0.48170835", "0.4803029", "0.47877732", "0.4784633", "0.47816327", "0.477287", "0.47652274", "0.4764624", "0.47553542", "0.47547063", "0.47534838", "0.47520316", "0.4751933", "0.47461146", "0.4745169", "0.47401366", "0.47355446", "0.4735503", "0.47334158", "0.47314677", "0.47287577", "0.47281963", "0.4724802", "0.4724802", "0.47176978", "0.47147554" ]
0.8349122
0
connect makes a connection to the collector server. It must be called with rc.mu held.
connect устанавливает соединение с сервером сбора данных. Его необходимо вызывать с держанием rc.mu.
func (rc *RemoteCollector) connect() error { if rc.pconn != nil { rc.pconn.Close() rc.pconn = nil } c, err := rc.dial() if err == nil { // Create a protobuf delimited writer wrapping the connection. When the // writer is closed, it also closes the underlying connection (see // source code for details). rc.pconn = pio.NewDelimitedWriter(c) } return err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s *Slave) connect(uri string, options Options) (err error) {\n\tdsn, opts, err := parseOptions(uri, options)\n\tif err != nil {\n\t\treturn\n\t}\n\tconn, err := newConn(context.Background(), dsn.Scheme, dsn.Host, opts)\n\tif err != nil {\n\t\treturn\n\t}\n\ts.c = conn\n\ts.cr = bufio.NewReaderSize(s.c.tcpConn, DefaultReaderBufSize)\n\t// for better error checking while writing to connection\n\ts.cw = bufio.NewWriter(s.c.tcpConn)\n\treturn\n}", "func (ch *ServerChannel) Connect(c *Client) {}", "func (c *Connection) connect(ctx context.Context) error {\n\tc.log.Debug(\"Connection: %s\",\n\t\tLogField{Key: ConnectionLogMsgKey, Value: \"dialing transport\"})\n\n\t// connect\n\ttransport, err := c.transport.Dial(ctx)\n\tif err != nil {\n\t\tc.log.Warning(\"Connection: error %s: %v\",\n\t\t\tLogField{Key: ConnectionLogMsgKey, Value: \"dialing transport\"},\n\t\t\tLogField{Key: \"error\", Value: err})\n\t\treturn err\n\t}\n\n\tclient := NewClient(transport, c.errorUnwrapper, c.tagsFunc)\n\tserver := NewServer(transport, c.wef)\n\n\tfor _, p := range c.protocols {\n\t\tif err := server.Register(p); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// call the connect handler\n\tc.log.Debug(\"Connection: %s\", LogField{Key: ConnectionLogMsgKey, Value: \"calling OnConnect\"})\n\terr = c.handler.OnConnect(ctx, c, client, server)\n\tif err != nil {\n\t\tc.log.Warning(\"Connection: error calling %s handler: %v\",\n\t\t\tLogField{Key: ConnectionLogMsgKey, Value: \"OnConnect\"},\n\t\t\tLogField{Key: \"error\", Value: err})\n\t\treturn err\n\t}\n\n\t// set the client for other callers.\n\t// we wait to do this so the handler has time to do\n\t// any setup required, e.g. authenticate.\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\tc.client = client\n\tc.server = server\n\tc.transport.Finalize()\n\n\tc.log.Debug(\"Connection: %s\", LogField{Key: ConnectionLogMsgKey, Value: \"connected\"})\n\treturn nil\n}", "func (c *Notification2Client) connect() error {\n\tif c.dialer == nil {\n\t\tpanic(\"Missing dialer for realtime client\")\n\t}\n\tws, err := c.createWebsocket()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.mtx.Lock()\n\tdefer c.mtx.Unlock()\n\n\tc.ws = ws\n\tif c.tomb == nil {\n\t\tc.tomb = &tomb.Tomb{}\n\t\tc.tomb.Go(c.worker)\n\t}\n\tc.connected = true\n\n\treturn nil\n}", "func (s *service) connect() {\n\tif s.destroyed {\n\t\ts.logger.Warnf(\"connect already destroyed\")\n\t\treturn\n\t}\n\n\taddr := fmt.Sprintf(\"%s:%d\", s.Host, s.Port)\n\n\ts.logger.Infof(\"start %s %s\", s.Name, addr)\n\n\ts.Connecting = true\n\tconn, err := net.Dial(\"tcp\", addr)\n\tfor err != nil {\n\t\tif s.destroyed {\n\t\t\ts.logger.Warnf(\"dial already destroyed\")\n\t\t\treturn\n\t\t}\n\t\tif s.restarted {\n\t\t\ts.logger.WithError(err).Warnf(\"dial %v\", err)\n\t\t} else {\n\t\t\ts.logger.WithError(err).Errorf(\"dial %v\", err)\n\t\t}\n\t\ttime.Sleep(time.Duration(1) * time.Second)\n\t\tconn, err = net.Dial(\"tcp\", addr)\n\t}\n\ts.conn = conn\n\ts.restarted = false\n\ts.Connecting = false\n\ts.logger.Infof(\"connected %s %s\", s.Name, addr)\n\n\tquit := make(chan struct{})\n\ts.Send = s.makeSendFun(conn)\n\tmsg := types.Message{\n\t\tRouterHeader: constants.RouterHeader.Connect,\n\t\tUserID: s.RouterID,\n\t\tPayloadURI: types.PayloadURI(s.Caller),\n\t}\n\ts.Send(msg)\n\tgo common.WithRecover(func() { s.readPump(conn, quit) }, \"read-pump\")\n\ts.startHB(conn, quit)\n}", "func (c *cpu) connect() {\n\tsp, addrlen := popU32(c.sp)\n\tsp, addr := popPtr(sp)\n\tfd := readI32(sp)\n\t_, _, err := syscall.Syscall(unix.SYS_CONNECT, uintptr(fd), addr, uintptr(addrlen))\n\tif strace {\n\t\tfmt.Fprintf(os.Stderr, \"connext(%#x, %#x, %#x) %v\\t; %s\\n\", fd, addr, addrlen, err, c.pos())\n\t}\n\tif err != 0 {\n\t\tc.setErrno(err)\n\t\twriteI32(c.rp, -1)\n\t\treturn\n\t}\n\n\twriteI32(c.rp, 0)\n}", "func (ch *InternalChannel) Connect(c *Client) {}", "func connect(pool chan *pooledClient, target *core.ServiceInstance) (Client, error) {\n\taddr := target.RemoteAddr.String()\n\tconn, err := net.Dial(\"tcp\", addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcountlog.Trace(\"event!client.connect\",\n\t\t\"qualifier\", target.Kind.Qualifier(),\n\t\t\"conn\", conn.LocalAddr())\n\tclt := &pooledClient{\n\t\tTCPConn: conn.(*net.TCPConn),\n\t\tpool: pool,\n\t\tcodec: codec.Codecs[target.Kind.Protocol],\n\t}\n\tclt.reader = bufio.NewReaderSize(clt, 2048)\n\treturn clt, nil\n}", "func (c *Config) connect() {\n\tc.emitEvent(Event{Type: EventConnected})\n}", "func (a *agent) connect() error {\n\terr := backoff.Retry(func() error {\n\t\tif a.amqpURL == \"\" {\n\t\t\treturn fmt.Errorf(\"no mq URL\")\n\t\t}\n\t\tparts := strings.Split(a.amqpURL, \"@\")\n\t\thostport := parts[len(parts)-1]\n\n\t\ta.logger.InfoF(\"dialing %q\", hostport)\n\t\tconn, err := amqp.Dial(a.amqpURL)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"dialing %q\", hostport)\n\t\t}\n\t\t// Set connection to agent for reference\n\t\ta.mu.Lock()\n\t\ta.conn = conn\n\t\ta.mu.Unlock()\n\n\t\tif err := a.openChannel(); err != nil {\n\t\t\treturn errors.Wrapf(err, \"openChannel\")\n\t\t}\n\n\t\tif err := a.runWorker(); err != nil {\n\t\t\treturn errors.Wrapf(err, \"startWorkers\")\n\t\t}\n\n\t\ta.wg.Add(1)\n\t\tgo func() {\n\t\t\tdefer a.wg.Done()\n\t\t\ta.waitChannel()\n\t\t}()\n\t\ta.logger.InfoF(\"connected %q\", hostport)\n\t\treturn nil\n\t}, backoff.WithContext(a.connBackOff, a.ctx))\n\tif err != nil {\n\t\ta.logger.ErrorF(\"connect failed: %q\", err.Error())\n\t\treturn err\n\t}\n\treturn nil\n}", "func (mon *SocketMonitor) Connect() error {\n\tenc := json.NewEncoder(mon.c)\n\tdec := json.NewDecoder(mon.c)\n\n\t// Check for banner on startup\n\tvar ban banner\n\tif err := dec.Decode(&ban); err != nil {\n\t\treturn err\n\t}\n\tmon.Version = &ban.QMP.Version\n\tmon.Capabilities = ban.QMP.Capabilities\n\n\t// Issue capabilities handshake\n\tcmd := Command{Execute: qmpCapabilities}\n\tif err := enc.Encode(cmd); err != nil {\n\t\treturn err\n\t}\n\n\t// Check for no error on return\n\tvar r response\n\tif err := dec.Decode(&r); err != nil {\n\t\treturn err\n\t}\n\tif err := r.Err(); err != nil {\n\t\treturn err\n\t}\n\n\t// Initialize socket listener for command responses and asynchronous\n\t// events\n\tevents := make(chan Event)\n\tstream := make(chan streamResponse)\n\tgo mon.listen(mon.c, events, stream)\n\n\tmon.events = events\n\tmon.stream = stream\n\n\treturn nil\n}", "func (ctl *Control) connectServer() (conn net.Conn, err error) {\n\treturn ctl.cm.Connect()\n}", "func (c *Easee) connect(ts oauth2.TokenSource) func() (signalr.Connection, error) {\n\tbo := backoff.NewExponentialBackOff()\n\tbo.MaxInterval = time.Minute\n\n\treturn func() (conn signalr.Connection, err error) {\n\t\tdefer func() {\n\t\t\tif err != nil {\n\t\t\t\ttime.Sleep(bo.NextBackOff())\n\t\t\t} else {\n\t\t\t\tbo.Reset()\n\t\t\t}\n\t\t}()\n\n\t\ttok, err := ts.Token()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tctx, cancel := context.WithTimeout(context.Background(), request.Timeout)\n\t\tdefer cancel()\n\n\t\treturn signalr.NewHTTPConnection(ctx, \"https://streams.easee.com/hubs/chargers\",\n\t\t\tsignalr.WithHTTPClient(c.Client),\n\t\t\tsignalr.WithHTTPHeaders(func() (res http.Header) {\n\t\t\t\treturn http.Header{\n\t\t\t\t\t\"Authorization\": []string{fmt.Sprintf(\"Bearer %s\", tok.AccessToken)},\n\t\t\t\t}\n\t\t\t}),\n\t\t)\n\t}\n}", "func (c *RedialConnection) connect() {\n\tif c.closed {\n\t\t// We don't really want to connect\n\t\treturn\n\t}\n\tif c.conn != nil && !c.conn.IsClosed() {\n\t\t// We already have a connection\n\t\treturn\n\t}\n\tfailCount := 0\n\tfor {\n\t\tconn, err := net.Dial(\"tcp\", c.address.String())\n\t\tif err == nil {\n\t\t\tc.conn = NewBasicConnection(conn, c.inbox)\n\t\t\treturn\n\t\t}\n\n\t\tfailCount++\n\t\ttimer := time.NewTimer(time.Duration(failCount) * time.Second)\n\t\tselect {\n\t\tcase <-c.quit:\n\t\t\treturn\n\t\tcase <-timer.C:\n\t\t\t// Looping again will try to reconnect\n\t\t}\n\t}\n}", "func (l *LogWriter) connect() {\n\tif l.connecting {\n\t\treturn\n\t}\n\tl.connecting = true\n\tvar err error\n\tfor l.conn == nil {\n\t\tl.conn, err = net.Dial(\"tcp\", l.Addr)\n\t\tif err != nil {\n\t\t\ttime.Sleep(time.Second)\n\t\t\tcontinue\n\t\t}\n\t\terr = l.sendMsg([]byte(fmt.Sprintf(\"!!cutelog!!format=%s\", l.Format)))\n\t\tif err != nil {\n\t\t\tl.Close()\n\t\t}\n\t}\n\tl.connecting = false\n}", "func (s *Server) connect() {\n\tln, err := net.Listen(\"tcp\", \":\"+strconv.Itoa(s.port))\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t} else {\n\t\ts.listener = ln\n\t\tlog.Println(\"Listening on port :\" + strconv.Itoa(s.port))\n\t}\n}", "func (d *RMQ) Connect() error { return nil }", "func (c *GatewayClient) connect() error {\n\tif !c.ready {\n\t\treturn errors.New(\"already tried to connect and failed\")\n\t}\n\n\tc.ready = false\n\tc.resuming = false\n\tc.heartbeatAcknowledged = true\n\tc.lastIdentify = time.Time{}\n\n\tc.Logf(\"connecting\")\n\t// TODO Need to set read deadline for hello packet and I also need to set write deadlines.\n\t// TODO also max message\n\tvar err error\n\tc.wsConn, _, err = websocket.DefaultDialer.Dial(c.GatewayURL, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgo c.manager()\n\n\treturn nil\n}", "func (s *Server) Connect(client *Client) {\n s.Clients.Store(client.Id, client)\n\n s.GM.Log.Debugf(\"Connecting new client %s\", client.Id)\n\n go client.Conn.Reader(client, s)\n go client.Conn.Writer(client, s)\n\n s.GM.FireEvent(NewDirectEvent(\"connected\", client, client.Id))\n}", "func (c *rpcclient) connect(ctx context.Context) (err error) {\n\tvar success bool\n\n\tc.clients = make([]*ethConn, 0, len(c.endpoints))\n\tc.neverConnectedEndpoints = make([]endpoint, 0, len(c.endpoints))\n\n\tfor _, endpoint := range c.endpoints {\n\t\tec, err := c.connectToEndpoint(ctx, endpoint)\n\t\tif err != nil {\n\t\t\tc.log.Errorf(\"Error connecting to %q: %v\", endpoint, err)\n\t\t\tc.neverConnectedEndpoints = append(c.neverConnectedEndpoints, endpoint)\n\t\t\tcontinue\n\t\t}\n\n\t\tdefer func() {\n\t\t\t// If all connections are outdated, we will not start, so close any open connections.\n\t\t\tif !success {\n\t\t\t\tec.Close()\n\t\t\t}\n\t\t}()\n\n\t\tc.clients = append(c.clients, ec)\n\t}\n\n\tsuccess = c.sortConnectionsByHealth(ctx)\n\n\tif !success {\n\t\treturn fmt.Errorf(\"failed to connect to an up-to-date ethereum node\")\n\t}\n\n\tgo c.monitorConnectionsHealth(ctx)\n\n\treturn nil\n}", "func (l *Logger) connect() (err error) {\n\tif l.conn != nil {\n\t\t// ignore err from close, it makes sense to continue anyway\n\t\tl.conn.close()\n\t\tl.conn = nil\n\t}\n\n\tif l.network == \"\" {\n\t\tl.conn, err = unixSyslog()\n\t\tif l.hostname == \"\" {\n\t\t\tl.hostname = \"localhost\"\n\t\t}\n\t} else {\n\t\tvar c net.Conn\n\t\tc, err = net.Dial(l.network, l.raddr)\n\t\tif err == nil {\n\t\t\tl.conn = &netConn{conn: c}\n\t\t\tif l.hostname == \"\" {\n\t\t\t\tl.hostname = c.LocalAddr().String()\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (r *CacheRedis) connect() {\n\n}", "func (c *client) Connect(ctx context.Context) error {\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tc.ctx = ctx\n\n\tremote := c.cfg.GetURL()\n\n\tvar subList []string\n\n\tfor topic := range c.SubscribedTopics {\n\t\tif IsPublicTopic(topic) {\n\t\t\tc.createCache(topic)\n\n\t\t\tsubList = append(subList, c.normalizeTopic(topic))\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif IsPrivateTopic(topic) && c.hasAuth() {\n\t\t\tc.createCache(topic)\n\n\t\t\tsubList = append(subList, c.normalizeTopic(topic))\n\t\t}\n\t}\n\n\tif len(subList) > 0 {\n\t\tremote.RawQuery = \"subscribe=\" + strings.Join(subList, \",\")\n\t}\n\n\tlog.Info(\"Connecting to: \", remote.String())\n\n\tconn, rsp, err := websocket.DefaultDialer.DialContext(\n\t\tctx, remote.String(), c.getHeader())\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Fail to connect[%s]: %v, %v\",\n\t\t\tremote.String(), err, rsp)\n\t}\n\n\tdefer func() {\n\t\tgo c.messageHandler()\n\t\tgo c.heartbeatHandler()\n\t}()\n\n\tc.ws = conn\n\tc.connected = true\n\tc.ws.SetCloseHandler(c.closeHandler)\n\n\treturn nil\n}", "func (m *MqttClientBase) connect() {\n\tif token := m.Client.Connect(); token.Wait() && token.Error() != nil {\n\t\tif !m.Connecting {\n\t\t\tlog.Printf(\"MQTT client %v\", token.Error())\n\t\t\tm.retryConnect()\n\t\t}\n\t}\n}", "func (self *discovery) connect() error {\n\n\tself.Lock()\n\tdefer self.Unlock()\n\n\tlog.Trace(\"[Discovery] Connecting\")\n\tif err := self.callDiscoveryService(\"multiregister\", true); err != nil {\n\t\tself.isMultiRegistered = false\n\t\treturn err\n\t}\n\n\t// now connected - set auth scope for service-to-service\n\t// @todo ask moddie if this is the place to do this?\n\t// I've put it here because i want the login service to work the same way, and it needs to message itself\n\tif serviceToServiceAuth {\n\t\tauth.SetCurrentService(Name)\n\t}\n\n\tself.isMultiRegistered = true\n\n\treturn nil\n}", "func (ch *Channel) Connect(c *Client) {\n ch.Clients.Store(c.Id, c)\n}", "func (w *Watcher) Connect(ctx context.Context, service string, conf bconf.Bconf) (sdr.SourceConn, error) {\n\treq := addService{\n\t\tctx: ctx,\n\t\tservice: service,\n\t\tdone: make(chan struct{}),\n\t}\n\tw.commCh <- &req\n\t<-req.done\n\tif req.conn == nil {\n\t\treturn nil, req.err\n\t}\n\treturn req.conn, req.err\n}", "func (rpc *LibvirtRPCMonitor) Connect() error {\n\treturn rpc.l.Connect()\n}", "func (a *amqpPubSub) connect(ctx context.Context) (*amqp.Session, error) {\n\turi, err := url.Parse(a.metadata.URL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclientOpts := a.createClientOptions(uri)\n\n\ta.logger.Infof(\"Attempting to connect to %s\", a.metadata.URL)\n\tclient, err := amqp.Dial(ctx, a.metadata.URL, &clientOpts)\n\tif err != nil {\n\t\ta.logger.Fatal(\"Dialing AMQP server:\", err)\n\t}\n\n\t// Open a session\n\tsession, err := client.NewSession(ctx, nil)\n\tif err != nil {\n\t\ta.logger.Fatal(\"Creating AMQP session:\", err)\n\t}\n\n\treturn session, nil\n}", "func (s *Service) Connect(ctx context.Context) error {\n\treturn s.Call(ctx, \"Connect\").Err\n}", "func (transport *IRCTransport) connect() error {\n\tvar conn net.Conn\n\tvar err error\n\t// Establish the connection.\n\tif transport.tlsConfig == nil {\n\t\ttransport.log.Infof(\"Connecting to %s...\", transport.server)\n\t\tconn, err = net.Dial(\"tcp\", transport.server)\n\t} else {\n\t\ttransport.log.Infof(\"Connecting to %s using TLS...\", transport.server)\n\t\tconn, err = tls.Dial(\"tcp\", transport.server, transport.tlsConfig)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Store connection.\n\ttransport.connection = conn\n\ttransport.decoder = irc.NewDecoder(conn)\n\ttransport.encoder = irc.NewEncoder(conn)\n\n\t// Send initial messages.\n\tif transport.password != \"\" {\n\t\ttransport.SendRawMessage(irc.PASS, []string{transport.password}, \"\")\n\t}\n\ttransport.SendRawMessage(irc.NICK, []string{transport.name}, \"\")\n\ttransport.SendRawMessage(irc.USER, []string{transport.user, \"0\", \"*\"}, transport.user)\n\n\ttransport.log.Debugf(\"Succesfully connected.\")\n\treturn nil\n}", "func (s *cinemaServiceServer) connect(ctx context.Context) (*sql.Conn, error) {\n\tc, err := s.db.Conn(ctx)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Unknown, \"failed to connect to database-> \"+err.Error())\n\t}\n\treturn c, nil\n}", "func (rhost *rhostData) connect() {\n\n\t// Get local IP list\n\tips, _ := rhost.getIPs()\n\n\t// Create command buffer\n\tbuf := new(bytes.Buffer)\n\t_, port := rhost.teo.td.GetAddr()\n\tbinary.Write(buf, binary.LittleEndian, byte(len(ips)))\n\tfor _, addr := range ips {\n\t\tbinary.Write(buf, binary.LittleEndian, []byte(addr))\n\t\tbinary.Write(buf, binary.LittleEndian, byte(0))\n\t}\n\tbinary.Write(buf, binary.LittleEndian, uint32(port))\n\tdata := buf.Bytes()\n\tfmt.Printf(\"Connect to r-host, send local IPs\\nip: %v\\nport: %d\\n\", ips, port)\n\n\t// Send command to r-host\n\trhost.teo.sendToTcd(rhost.tcd, CmdConnectR, data)\n\trhost.connected = true\n}", "func Connect(config *viper.Viper) (Connection, error) {\n\tvar c Connection\n\n\terr := c.InitLog(\"\")\n\tif err != nil {\n\t\treturn c, err\n\t}\n\n\thost := config.GetString(\"server.host\")\n\tport := config.GetString(\"server.controlPort\")\n\n\tserver := host + \":\" + port\n\tc.connection, err = net.Dial(\"tcp\", server)\n\tif err != nil {\n\t\treturn c, err\n\t}\n\n\treturn c, nil\n}", "func connect() (client *mongo.Client) {\n\tclient, err := mongo.NewClient(options.Client().ApplyURI(NEWSURI))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\terr = client.Connect(ctx)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn client\n}", "func (c *NATSTestClient) Connect() error {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\tc.subs = make(map[string]*Subscription)\n\tc.reqs = make(chan *Request, 256)\n\tc.connected = true\n\treturn nil\n}", "func (m *MongoDB) connect() error {\n\tvar url string\n\tif m.config.GetUser() != \"\" {\n\t\turl = m.config.GetUser()\n\t}\n\tif m.config.GetPassword() != \"\" {\n\t\turl += \":\" + m.config.GetPassword()\n\t}\n\tif m.config.GetUser() != \"\" || m.config.GetPassword() != \"\" {\n\t\turl += \"@\"\n\t}\n\turl += m.config.GetHost() + \":\" + strconv.Itoa(m.config.GetPort())\n\n\tsession, err := mgo.Dial(\"mongodb://\" + url)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tm.db = session.DB(m.config.GetDatabase())\n\tm.db.Session = session\n\treturn nil\n}", "func (n *Node) connect(entryPoint *peer.Peer) *NodeErr {\n\t// Create the request using a connection message.\n\tmsg := new(message.Message).SetType(message.ConnectType).SetFrom(n.Self)\n\treq, err := composeRequest(msg, entryPoint)\n\tif err != nil {\n\t\treturn ParseErr(\"error encoding message to request\", err)\n\t}\n\n\t// Try to join into the network through the provided peer\n\tres, err := n.client.Do(req)\n\tif err != nil {\n\t\treturn ConnErr(\"error trying to connect to a peer\", err)\n\t}\n\n\tif code := res.StatusCode; code != http.StatusOK {\n\t\terr := fmt.Errorf(\"%d http status received from %s\", code, entryPoint)\n\t\treturn ConnErr(\"error making the request to a peer\", err)\n\t}\n\n\t// Reading the list of current members of the network from the peer\n\t// response.\n\tbody, err := io.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn ParseErr(\"error reading peer response body\", err)\n\t}\n\tres.Body.Close()\n\n\t// Parsing the received list\n\treceivedMembers := peer.NewMembers()\n\tif receivedMembers, err = receivedMembers.FromJSON(body); err != nil {\n\t\treturn ParseErr(\"error parsing incoming member list\", err)\n\t}\n\n\t// Update current members and send a connection request to all of them,\n\t// discarting the response received (the list of current members).\n\tfor _, member := range receivedMembers.Peers() {\n\t\t// If a received peer is not the same that contains the current node try\n\t\t// to connect directly.\n\t\tif !n.Self.Equal(member) {\n\t\t\tif req, err := composeRequest(msg, member); err != nil {\n\t\t\t\treturn ParseErr(\"error decoding request to message\", err)\n\t\t\t} else if _, err := n.client.Do(req); err != nil {\n\t\t\t\treturn ConnErr(\"error trying to perform the request\", err)\n\t\t\t}\n\t\t\tn.Members.Append(member)\n\t\t}\n\t}\n\n\t// Set node status as connected.\n\tn.setConnected(true)\n\t// Append the entrypoint to the current members.\n\tn.Members.Append(entryPoint)\n\treturn nil\n}", "func (a *Agent) Connect() error {\n\tfor _, sink := range a.Config.Sinks {\n\t\tswitch st := sink.Sink.(type) {\n\t\tcase optic.ServiceSink:\n\t\t\tif err := st.Start(); err != nil {\n\t\t\t\tlog.Printf(\"ERROR Service for sink '%s' failed to start, exiting\\n%s\\n\",\n\t\t\t\t\tsink.Name(), err.Error())\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tlog.Printf(\"DEBUG Attempting connection to sink: %s\\n\", sink.Config.Name)\n\n\t\terr := sink.Sink.Connect()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"ERROR Failed to connect to sink %s, retrying in 15s, error was '%s' \\n\",\n\t\t\t\tsink.Name(), err)\n\t\t\ttime.Sleep(15 * time.Second)\n\t\t\terr = sink.Sink.Connect()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tlog.Printf(\"DEBUG Successfully connected to sink: %s\\n\", sink.Config.Name)\n\t}\n\treturn nil\n}", "func (e *ECU) authConnect(ctx *ipc.Context) (*conn.Seesaw, error) {\n\tif ctx == nil {\n\t\treturn nil, errors.New(\"context is nil\")\n\t}\n\tauthCtx, err := e.authenticate(ctx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"authentication failed: %v\", err)\n\t}\n\n\tseesawConn, err := conn.NewSeesawIPC(authCtx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to connect to engine: %v\", err)\n\t}\n\tif err := seesawConn.Dial(e.cfg.EngineSocket); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to connect to engine: %v\", err)\n\t}\n\n\treturn seesawConn, nil\n}", "func connect(dialOpts *DialOpts, grpcServer *grpc.Server, yDialer *YamuxDialer) error {\n\t// dial underlying tcp connection\n\tvar conn net.Conn\n\tvar err error\n\n\tif dialOpts.TLS {\n\t\t// use tls\n\t\tcfg := dialOpts.TLSConfig\n\t\tif cfg == nil {\n\t\t\tcfg = &tls.Config{}\n\t\t}\n\t\tconn, err = tls.Dial(\"tcp\", dialOpts.Addr, cfg)\n\n\t} else {\n\t\tconn, err = (&net.Dialer{}).DialContext(context.Background(), \"tcp\", dialOpts.Addr)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\n\tsession, err := yamux.Client(conn, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer session.Close()\n\n\t// now that we have a connection, create both clients & servers\n\n\t// setup client\n\tyDialer.SetSession(session)\n\n\t// start grpc server in a separate goroutine. this will exit when the\n\t// underlying session (conn) closes and clean itself up.\n\tgo grpcServer.Serve(session)\n\n\t// return when the conn closes so we can try reconnecting\n\t<-session.CloseChan()\n\treturn nil\n}", "func (b *Backend) connect() (*Op, error) {\n\tif b.session != nil {\n\t\tb.session.Refresh()\n\t\treturn b.newOp(), nil\n\t}\n\tsession, err := b.dial()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.session = session\n\terr = b.createMongoIndexes()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn b.newOp(), nil\n}", "func (c *Client) connect() (conn *net.TCPConn, err error) {\n\n\ttype DialResp struct {\n\t\tConn *net.TCPConn\n\t\tError error\n\t}\n\n\t// Open connection to Zabbix host\n\tiaddr, err := c.getTCPAddr()\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// dial tcp and handle timeouts\n\tch := make(chan DialResp)\n\n\tgo func() {\n\t\tconn, err = net.DialTCP(\"tcp\", nil, iaddr)\n\t\tch <- DialResp{Conn: conn, Error: err}\n\t}()\n\n\tselect {\n\tcase <-time.After(5 * time.Second):\n\t\terr = fmt.Errorf(\"Connection Timeout\")\n\tcase resp := <-ch:\n\t\tif resp.Error != nil {\n\t\t\terr = resp.Error\n\t\t\tbreak\n\t\t}\n\n\t\tconn = resp.Conn\n\t}\n\n\treturn\n}", "func connect(\n\tladdr string,\n\traddr string,\n\tproto uint,\n\thbint time.Duration,\n) *net.IPConn {\n\tc, err := net.DialIP(\n\t\tfmt.Sprintf(\"ip:%v\", proto),\n\t\tresolve(laddr),\n\t\tresolve(raddr),\n\t)\n\tif nil != err {\n\t\tlog.Fatalf(\"Dial: %v\", err)\n\t}\n\n\t/* Start to heartbeet */\n\tgo heartbeet(c, hbint)\n\n\treturn c\n}", "func connect() ([]client.Client, error) {\n\treturn influx.ConnectService(\"MDS_DB_ADDRESS\", MDS_PORT, \"MDS_USER\", \"MDS_PASSWORD\")\n}", "func (d *DBGenerator) connect(ctx context.Context) error {\n\tif d.Conn == nil {\n\t\tconnStr := fmt.Sprintf(\"vertica://%s:%s@%s:%d/%s?tlsmode=%s\",\n\t\t\td.Opts.User, d.Opts.Password, d.Opts.Host, d.Opts.Port, d.Opts.DBName, d.Opts.TLSMode,\n\t\t)\n\t\tconn, err := sql.Open(\"vertica\", connStr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\td.Conn = conn\n\t}\n\n\treturn d.Conn.PingContext(ctx)\n}", "func (z *ZkRegistry) connect() error {\n\tif !z.isConnected() {\n\t\tconn, connChan, err := zk.Connect(z.NodeParams.Servers, time.Second)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfor {\n\t\t\tisConnected := false\n\n\t\t\tselect {\n\t\t\tcase connEvent := <-connChan:\n\t\t\t\tif connEvent.State == zk.StateConnected {\n\t\t\t\t\tisConnected = true\n\t\t\t\t}\n\t\t\tcase _ = <-time.After(time.Second * 3):\n\t\t\t\treturn errors.New(\"Connect to zookeeper server timeout!\")\n\t\t\t}\n\n\t\t\tif isConnected {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\terr = conn.AddAuth(\"digest\", []byte(z.node.User.UserName+\":\"+z.node.User.Password))\n\t\tif err != nil {\n\t\t\treturn errors.New(\"AddAuth error: \\n\" + err.Error())\n\t\t}\n\n\t\tz.Conn = conn\n\t}\n\n\treturn nil\n}", "func (s *Sender) connect() net.Conn {\n\tbaseGap := 500 * time.Millisecond\n\tfor {\n\t\tconn, err := net.Dial(\"tcp\", s.addr)\n\t\tif err != nil {\n\t\t\tlog.Print(err)\n\t\t\ttime.Sleep(baseGap)\n\t\t\tbaseGap *= 2\n\t\t\tif baseGap > time.Second*30 {\n\t\t\t\tbaseGap = time.Second * 30\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tdebugInfo(fmt.Sprintf(\"local addr:%s\\n\", conn.LocalAddr()))\n\t\treturn conn\n\t}\n}", "func connect() (*websocket.Conn, error) {\n\thost := fmt.Sprintf(\"%s:%s\", configuration.TV.Host, *configuration.TV.Port)\n\tpath := \"/api/v2/channels/samsung.remote.control\"\n\tquery := fmt.Sprintf(\"name=%s\", base64.StdEncoding.EncodeToString([]byte(configuration.Controller.Name)))\n\tu := url.URL{Scheme: *configuration.TV.Protocol, Host: host, Path: path, RawQuery: query}\n\n\tlog.Infof(\"Opening connection to %s ...\", u.String())\n\n\twebsocket.DefaultDialer.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}\n\n\tconnection, _, err := websocket.DefaultDialer.Dial(u.String(), nil)\n\tif err != nil {\n\t\tlog.Debugf(\"%v\", err)\n\t\treturn nil, err\n\t}\n\n\tlog.Infof(\"Connection is established.\")\n\n\treturn connection, nil\n}", "func (cg *CandlesGroup) connect() {\n\tcg.wsClient = websocket.NewClient(wsURL, cg.httpProxy)\n\tif err := cg.wsClient.Connect(); err != nil {\n\t\tlog.Println(\"[BITFINEX] Error connecting to bitfinex API: \", err)\n\t\tcg.restart()\n\t\treturn\n\t}\n\tcg.wsClient.Listen(cg.bus.dch, cg.bus.ech)\n}", "func connect() *r.Session {\n\tsession, _ := r.Connect(r.ConnectOpts{\n\t\tAddress: \"localhost:28015\",\n\t})\n\treturn session\n}", "func (pe *providerEndpoint) Connect(args *ConnectRequest, resp *ConnectResponse) error {\n\tdefer metrics.IncrCounter([]string{\"scada\", \"connect\", args.Capability}, 1)\n\tpe.p.logger.Printf(\"[INFO] scada-client: connect requested (capability: %s)\",\n\t\targs.Capability)\n\n\t// Handle potential flash\n\tif args.Severity != \"\" && args.Message != \"\" {\n\t\tpe.p.logger.Printf(\"[%s] scada-client: %s\", args.Severity, args.Message)\n\t}\n\n\t// Look for the handler\n\thandler := pe.p.config.Handlers[args.Capability]\n\tif handler == nil {\n\t\tpe.p.logger.Printf(\"[WARN] scada-client: requested capability '%s' not available\",\n\t\t\targs.Capability)\n\t\treturn fmt.Errorf(\"invalid capability\")\n\t}\n\n\t// Hijack the connection\n\tpe.setHijack(func(a io.ReadWriteCloser) {\n\t\tif err := handler(args.Capability, args.Meta, a); err != nil {\n\t\t\tpe.p.logger.Printf(\"[ERR] scada-client: '%s' handler error: %v\",\n\t\t\t\targs.Capability, err)\n\t\t}\n\t})\n\tresp.Success = true\n\treturn nil\n}", "func connect(ctx context.Context, session liveshare.LiveshareSession) (Invoker, error) {\n\tlistener, err := listenTCP()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlocalAddress := listener.Addr().String()\n\n\tinvoker := &invoker{\n\t\tsession: session,\n\t\tlistener: listener,\n\t}\n\n\t// Create a cancelable context to be able to cancel background tasks\n\t// if we encounter an error while connecting to the gRPC server\n\tconnectctx, cancel := context.WithCancel(context.Background())\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tcancel()\n\t\t}\n\t}()\n\n\tch := make(chan error, 2) // Buffered channel to ensure we don't block on the goroutine\n\n\t// Ensure we close the port forwarder if we encounter an error\n\t// or once the gRPC connection is closed. pfcancel is retained\n\t// to close the PF whenever we close the gRPC connection.\n\tpfctx, pfcancel := context.WithCancel(connectctx)\n\tinvoker.cancelPF = pfcancel\n\n\t// Tunnel the remote gRPC server port to the local port\n\tgo func() {\n\t\tfwd := liveshare.NewPortForwarder(session, codespacesInternalSessionName, codespacesInternalPort, true)\n\t\tch <- fwd.ForwardToListener(pfctx, listener)\n\t}()\n\n\tvar conn *grpc.ClientConn\n\tgo func() {\n\t\t// Attempt to connect to the port\n\t\topts := []grpc.DialOption{\n\t\t\tgrpc.WithTransportCredentials(insecure.NewCredentials()),\n\t\t\tgrpc.WithBlock(),\n\t\t}\n\t\tconn, err = grpc.DialContext(connectctx, localAddress, opts...)\n\t\tch <- err // nil if we successfully connected\n\t}()\n\n\t// Wait for the connection to be established or for the context to be cancelled\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn nil, ctx.Err()\n\tcase err := <-ch:\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tinvoker.conn = conn\n\tinvoker.jupyterClient = jupyter.NewJupyterServerHostClient(conn)\n\tinvoker.codespaceClient = codespace.NewCodespaceHostClient(conn)\n\tinvoker.sshClient = ssh.NewSshServerHostClient(conn)\n\n\t// Send initial connection heartbeat (no need to throw if we fail to get a response from the server)\n\t_ = invoker.notifyCodespaceOfClientActivity(ctx, connectedEventName)\n\n\t// Start the activity heatbeats\n\tgo invoker.heartbeat(pfctx, 1*time.Minute)\n\n\treturn invoker, nil\n}", "func (h *Handler) Connect(ctx context.Context, in *backend.StatusRequest, out *backend.StatusResponse) error {\n\t// nothing to do\n\treturn nil\n}", "func (m *MysqlRepository) connect() error {\n\tif !m.connected {\n\t\tdb, err := sql.Open(\"mysql\", m.Credentials)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tm.db = db\n\t\tm.connected = true\n\t}\n\n\treturn nil\n}", "func connect() (Publisher, error) {\n\tif publisher != nil {\n\t\treturn publisher, nil\n\t}\n\tconfigNSQ := nsq.NewConfig()\n\tclient, err := nsq.NewProducer(os.Getenv(\"NSQ_PUBLISHER\"), configNSQ)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient.SetLogger(nullLogger, nsq.LogLevelInfo)\n\tpublisher = &Produce{\n\t\tInstance: client,\n\t}\n\treturn publisher, nil\n}", "func (kms *kmipKMS) connect() (*tls.Conn, error) {\n\tconn, err := tls.Dial(\"tcp\", kms.endpoint, kms.tlsConfig)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to dial kmip connection endpoint: %w\", err)\n\t}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tconn.Close()\n\t\t}\n\t}()\n\tif kms.readTimeout != 0 {\n\t\terr = conn.SetReadDeadline(time.Now().Add(time.Second * time.Duration(kms.readTimeout)))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to set read deadline: %w\", err)\n\t\t}\n\t}\n\tif kms.writeTimeout != 0 {\n\t\terr = conn.SetReadDeadline(time.Now().Add(time.Second * time.Duration(kms.writeTimeout)))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to set write deadline: %w\", err)\n\t\t}\n\t}\n\n\terr = conn.Handshake()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to perform connection handshake: %w\", err)\n\t}\n\n\terr = kms.discover(conn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn conn, nil\n}", "func (h *Health) Connect() error {\n\tauthHandler := internal.BasicAuthHandler(h.BasicUsername, h.BasicPassword, \"health\", onAuthError)\n\n\th.server = &http.Server{\n\t\tAddr: h.ServiceAddress,\n\t\tHandler: authHandler(h),\n\t\tReadTimeout: time.Duration(h.ReadTimeout),\n\t\tWriteTimeout: time.Duration(h.WriteTimeout),\n\t\tTLSConfig: h.tlsConf,\n\t}\n\n\tlistener, err := h.listen()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\th.origin = h.getOrigin(listener)\n\n\th.Log.Infof(\"Listening on %s\", h.origin)\n\n\th.wg.Add(1)\n\tgo func() {\n\t\tdefer h.wg.Done()\n\t\terr := h.server.Serve(listener)\n\t\tif err != http.ErrServerClosed {\n\t\t\th.Log.Errorf(\"Serve error on %s: %v\", h.origin, err)\n\t\t}\n\t\th.origin = \"\"\n\t}()\n\n\treturn nil\n}", "func (s *MQ) connect(name string) (*amqp.Connection, error) {\n\tif name == \"\" {\n\t\tname = s.ConnectionName\n\t}\n\tif name == \"\" {\n\t\tname = s.name\n\t}\n\ts.Log(\"connecting %q\", name)\n\n\tvar heartBeat = s.HeartBeat\n\tif heartBeat == 0 {\n\t\theartBeat = 10\n\t}\n\n\t// Use the user provided client name\n\tconnection, err := amqp.DialConfig(s.Url, amqp.Config{\n\t\tHeartbeat: time.Duration(heartBeat) * time.Second,\n\t\tProperties: amqp.Table{\n\t\t\t\"product\": s.Product,\n\t\t\t\"version\": s.Version,\n\t\t\t\"connection_name\": name,\n\t\t},\n\t\tLocale: \"en_US\",\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts.Log(\"connected\")\n\treturn connection, nil\n}", "func (network *tcp_net) connect(channels int) {\n\t// Resolving address of endpoint\n\taddr, err := net.ResolveTCPAddr(\"tcp\", network.api.endpoint)\n\tif err != nil {\n\t\tgo network.api.trigger_local(EVENT_ON_ERROR,\n\t\t\t[]byte(fmt.Sprintf(\"Unable to resolve given endpoint %s from TCP -> %s\", network.api.endpoint, err.Error())))\n\t\treturn\n\t}\n\n\t// getting handshake from TreeApi\n\thandshake_data := network.api.firstHandshake()\n\n\tfor i := 0; i < channels; i++ {\n\t\tconn, err := net.DialTCP(\"tcp\", nil, addr)\n\t\tif err != nil {\n\t\t\tgo network.api.trigger_local(EVENT_ON_ERROR,\n\t\t\t\t[]byte(fmt.Sprintf(\"Unable to connect to given endpoint %s from TCP -> %s\", network.api.endpoint, err.Error())))\n\t\t} else {\n\t\t\tnetwork.connection_locker.Lock()\n\t\t\tnetwork.connections[tcp_conn_index] = conn\n\t\t\tgo network.handle_connection(tcp_conn_index, conn, handshake_data)\n\t\t\tgo network.api.trigger_local(EVENT_ON_CHANNEL_CONNECTION, []byte{})\n\t\t\ttcp_conn_index++\n\t\t\tnetwork.connection_locker.Unlock()\n\t\t}\n\t}\n}", "func (ds *gcdatastore) connect() (err error) {\n\tctx := context.Background()\n\n\tds.Client, err = datastore.NewClient(ctx, ds.gcloudProjectID, ds.gcloudClientOpts...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (conn *Conn) internalConnect(ctx context.Context) error {\n\tconn.mu.Lock()\n\tdefer conn.mu.Unlock()\n\tconn.initialise()\n\n\tif conn.cfg.Server == \"\" {\n\t\treturn fmt.Errorf(\"irc.Connect(): cfg.Server must be non-empty\")\n\t}\n\tif conn.connected {\n\t\treturn fmt.Errorf(\"irc.Connect(): Cannot connect to %s, already connected.\", conn.cfg.Server)\n\t}\n\n\tif !hasPort(conn.cfg.Server) {\n\t\tif conn.cfg.SSL {\n\t\t\tconn.cfg.Server = net.JoinHostPort(conn.cfg.Server, \"6697\")\n\t\t} else {\n\t\t\tconn.cfg.Server = net.JoinHostPort(conn.cfg.Server, \"6667\")\n\t\t}\n\t}\n\n\tif conn.cfg.Proxy != \"\" {\n\t\tproxyURL, err := url.Parse(conn.cfg.Proxy)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tproxyDialer, err := proxy.FromURL(proxyURL, conn.dialer)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcontextProxyDialer, ok := proxyDialer.(proxy.ContextDialer)\n\t\tif !ok {\n\t\t\treturn errors.New(\"Dialer for proxy does not support context\")\n\t\t}\n\t\tconn.proxyDialer = contextProxyDialer\n\t\tlogging.Info(\"irc.Connect(): Connecting to %s.\", conn.cfg.Server)\n\t\tif s, err := conn.proxyDialer.DialContext(ctx, \"tcp\", conn.cfg.Server); err == nil {\n\t\t\tconn.sock = s\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tlogging.Info(\"irc.Connect(): Connecting to %s.\", conn.cfg.Server)\n\t\tif s, err := conn.dialer.DialContext(ctx, \"tcp\", conn.cfg.Server); err == nil {\n\t\t\tconn.sock = s\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif conn.cfg.SSL {\n\t\tlogging.Info(\"irc.Connect(): Performing SSL handshake.\")\n\t\ts := tls.Client(conn.sock, conn.cfg.SSLConfig)\n\t\tif err := s.Handshake(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tconn.sock = s\n\t}\n\n\tconn.postConnect(ctx, true)\n\tconn.connected = true\n\treturn nil\n}", "func (observer *Observer) Connect(id int32, port int32) {\n\tobserver.connector.Connect(id, port)\n}", "func (s *Stackdriver) Connect() error {\n\tif s.Project == \"\" {\n\t\treturn fmt.Errorf(\"project is a required field for stackdriver output\")\n\t}\n\n\tif s.Namespace == \"\" {\n\t\ts.Log.Warn(\"plugin-level namespace is empty\")\n\t}\n\n\tif s.ResourceType == \"\" {\n\t\ts.ResourceType = \"global\"\n\t}\n\n\tif s.ResourceLabels == nil {\n\t\ts.ResourceLabels = make(map[string]string, 1)\n\t}\n\n\tif s.counterCache == nil {\n\t\ts.counterCache = NewCounterCache(s.Log)\n\t}\n\n\ts.ResourceLabels[\"project_id\"] = s.Project\n\n\tif s.client == nil {\n\t\tctx := context.Background()\n\t\tclient, err := monitoring.NewMetricClient(ctx, option.WithUserAgent(internal.ProductToken()))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ts.client = client\n\t}\n\n\treturn nil\n}", "func connect() *websocket.Conn {\n\turl := url.URL{Scheme: \"ws\", Host: *addr, Path: \"/ws\"}\n\tlog.Info(\"Connecting to \", url.String())\n\tconn, _, err := dialer.Dial(url.String(), nil)\n\tcheckError(err)\n\tlog.Info(\"Connected to \", url.String())\n\n\t// Read the message from server with deadline of ResponseWait(30) seconds\n\tconn.SetReadDeadline(time.Now().Add(utils.ResponseWait * time.Second))\n\n\treturn conn\n}", "func (a *Agent) connect(addrs []string) {\n\n\tfor _, addr := range addrs {\n\t\tconn, err := net.Dial(\"tcp\", addr)\n\t\tif err != nil {\n\t\t\t// warn := fmt.Sprintf(\"could not connect to '%s' : %v\", addr, err)\n\t\t\t// a.warningCh <- warn\n\t\t\tcontinue\n\t\t}\n\t\ta.logger.Printf(\"[INFO] node '%v' : established an outgoing connection to peer with address %v\", a.ID(), conn.LocalAddr().String())\n\t\t// peer := NewPeer(conn)\n\t\t// if err := peerManager.Handshake(peer); err != nil {\n\t\t// \tlog.Fatalf(\"Error adding initial peer %s: %s\", peer, err)\n\t\t// }\n\t}\n}", "func (bp *Processer) Connect(addr string) (err error) {\n\tbp.log(\"Connect:%s\", addr)\n\tbp.CloseServer()\n\tbp.svr, err = GetServer(addr)\n\tif err != nil {\n\t\treturn\n\t}\n\tbp.svr.AddProcesser(bp, 0)\n\tbp.log(\"Connect finish \")\n\treturn\n}", "func (c *Client) Connect(url *common.URL) error {\n\tinitClient(url.Protocol)\n\tc.conf = *clientConf\n\tc.sslEnabled = c.conf.SSLEnabled\n\t// codec\n\tc.codec = remoting.GetCodec(url.Protocol)\n\tc.addr = url.Location\n\t_, _, err := c.selectSession(c.addr)\n\tif err != nil {\n\t\tlogger.Errorf(\"try to connect server %v failed for : %v\", url.Location, err)\n\t}\n\treturn err\n}", "func (l *Writer) connect() error {\n\tif l.writer != nil {\n\t\tl.writer.Close()\n\t\tl.writer = nil\n\t}\n\n\tc, err := net.Dial(\"udp\", l.raddr)\n\tif err == nil {\n\t\tl.writer = c\n\t}\n\treturn err\n}", "func (s *MultipassServer) Connect(ctx context.Context, request *apigrpc.ConnectRequest) (*apigrpc.ConnectReply, error) {\n\tglog.V(5).Infof(\"Call server Connect: %v\", request)\n\n\tif request.GetProviderID() != s.Configuration.ProviderID {\n\t\tglog.Errorf(errMismatchingProvider)\n\t\treturn nil, fmt.Errorf(errMismatchingProvider)\n\t}\n\n\tif request.GetResourceLimiter() != nil {\n\t\ts.ResourceLimiter = &ResourceLimiter{\n\t\t\tMinLimits: request.ResourceLimiter.MinLimits,\n\t\t\tMaxLimits: request.ResourceLimiter.MaxLimits,\n\t\t}\n\t}\n\n\ts.NodesDefinition = request.GetNodes()\n\ts.AutoProvision = request.GetAutoProvisionned()\n\n\tif request.GetKubeAdmConfiguration() != nil {\n\t\ts.KubeAdmConfiguration = request.GetKubeAdmConfiguration()\n\t}\n\n\tif s.AutoProvision {\n\t\tif err := s.doAutoProvision(); err != nil {\n\t\t\tglog.Errorf(errUnableToAutoProvisionNodeGroup, err)\n\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &apigrpc.ConnectReply{\n\t\tResponse: &apigrpc.ConnectReply_Connected{\n\t\t\tConnected: true,\n\t\t},\n\t}, nil\n}", "func (c *client) Connect(ctx context.Context) error {\n\tctx, cancel := context.WithTimeout(ctx, c.timeout)\n\tdefer cancel()\n\n\tconn, err := grpc.DialContext(ctx, c.uri, grpc.WithInsecure(), grpc.WithBlock())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not connect to store at %s: %w\", c.uri, err)\n\t}\n\n\tc.services = &services{\n\t\tkvc: eventstore.NewKVClient(conn),\n\t\tmapc: eventstore.NewMapClient(conn),\n\t\tqueuec: eventstore.NewQueueClient(conn),\n\t}\n\n\treturn nil\n}", "func (rc *Store) connectInit() error {\n\trc.conn = memcache.New(rc.conninfo...)\n\treturn nil\n}", "func connect() {\n\tconn, err := http.NewConnection(http.ConnectionConfig{\n\t\tEndpoints: []string{hlp.Conf.DB.URL},\n\t})\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to create HTTP connection: %v\", err)\n\t}\n\n\tclient, err := driver.NewClient(driver.ClientConfig{\n\t\tConnection: conn,\n\t\tAuthentication: driver.BasicAuthentication(\n\t\t\thlp.Conf.DB.User,\n\t\t\thlp.Conf.DB.Pass,\n\t\t),\n\t})\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to create new client: %v\", err)\n\t}\n\n\tctx := context.Background()\n\tdb, err := client.Database(ctx, \"cardo_dev\")\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to open database: %v\", err)\n\t}\n\n\tDatabase = db\n}", "func connectRemote() {\n\taddress := *server + \":\" + *port\n\tfmt.Println(\"Attempting to connect to remote @\" + address)\n\tconn, err := net.Dial(\"tcp\", address)\n\tif err != nil {\n\t\tremoteError(err)\n\t}\n\tfmt.Println(\"Connected to remote @\" + address)\n\tRemoteServer = conn\n\n\t//TODO reply to the keep alive messages?\n\n}", "func (c *Connection) Start(options connection.ConnectOptions) (err error) {\n\tvar config wg.ServiceConfig\n\tif err := json.Unmarshal(options.SessionConfig, &config); err != nil {\n\t\treturn errors.Wrap(err, \"failed to unmarshal connection config\")\n\t}\n\tc.config.Provider = config.Provider\n\tc.config.Consumer.IPAddress = config.Consumer.IPAddress\n\n\t// We do not need port mapping for consumer, since it initiates the session\n\tfakePortMapper := func(port int) (releasePortMapping func()) {\n\t\treturn func() {}\n\t}\n\n\tresourceAllocator := connectionResourceAllocator()\n\tc.connectionEndpoint, err = endpoint.NewConnectionEndpoint(location.ServiceLocationInfo{}, resourceAllocator, fakePortMapper, 0)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to create new connection endpoint\")\n\t}\n\n\tc.connection.Add(1)\n\tc.stateChannel <- connection.Connecting\n\n\tif err := c.connectionEndpoint.Start(&c.config); err != nil {\n\t\tc.stateChannel <- connection.NotConnected\n\t\tc.connection.Done()\n\t\treturn errors.Wrap(err, \"failed to start connection endpoint\")\n\t}\n\n\t// Provider requests to delay consumer connection since it might be in a process of setting up NAT traversal for given consumer\n\tif config.Consumer.ConnectDelay > 0 {\n\t\tlog.Infof(\"%s delaying connect for %v milliseconds\", logPrefix, config.Consumer.ConnectDelay)\n\t\ttime.Sleep(time.Duration(config.Consumer.ConnectDelay) * time.Millisecond)\n\t}\n\n\tif err := c.connectionEndpoint.AddPeer(c.config.Provider.PublicKey, &c.config.Provider.Endpoint); err != nil {\n\t\tc.stateChannel <- connection.NotConnected\n\t\tc.connection.Done()\n\t\treturn errors.Wrap(err, \"failed to add peer to the connection endpoint\")\n\t}\n\n\tif err := c.connectionEndpoint.ConfigureRoutes(c.config.Provider.Endpoint.IP); err != nil {\n\t\tc.stateChannel <- connection.NotConnected\n\t\tc.connection.Done()\n\t\treturn errors.Wrap(err, \"failed to configure routes for connection endpoint\")\n\t}\n\n\tif err := c.waitHandshake(); err != nil {\n\t\tc.stateChannel <- connection.NotConnected\n\t\tc.connection.Done()\n\t\treturn errors.Wrap(err, \"failed while waiting for a peer handshake\")\n\t}\n\n\tgo c.runPeriodically(time.Second)\n\n\tc.stateChannel <- connection.Connected\n\treturn nil\n}", "func connect(host string) (*ldap.Conn, error) {\n\tc, err := net.DialTimeout(\"tcp\", host, time.Second*8)\n\tif err != nil {\n\t\tWriteLogFile(err)\n\t\treturn nil, err\n\t}\n\tconn := ldap.NewConn(c, false)\n\tconn.Start()\n\treturn conn, nil\n}", "func Connect(ctx context.Context, drCSIAddress string, metricsManager metrics.CSIMetricsManager) (conn *grpc.ClientConn, err error) {\n\tvar m sync.Mutex\n\tvar canceled bool\n\tready := make(chan bool)\n\tgo func() {\n\t\tconn, err = connection.Connect(drCSIAddress, metricsManager)\n\n\t\tm.Lock()\n\t\tdefer m.Unlock()\n\t\tif err != nil && canceled {\n\t\t\t_ = conn.Close()\n\t\t}\n\n\t\tclose(ready)\n\t}()\n\n\tselect {\n\tcase <-ctx.Done():\n\t\tm.Lock()\n\t\tdefer m.Unlock()\n\t\tcanceled = true\n\t\treturn nil, ctx.Err()\n\n\tcase <-ready:\n\t\treturn conn, err\n\t}\n}", "func (a *Application) Connect(conn *connection.Connection) {\n\tlog.Infof(\"adding a new Connection %s to Application %s\", conn.SocketID, a.Name)\n\ta.Lock()\n\tdefer a.Unlock()\n\n\ta.connections[conn.SocketID] = conn\n\n\ta.Stats.Add(\"TotalConnections\", 1)\n}", "func (client *Client) connect(connType string) net.Conn {\n\tconn, err := net.Dial(connType, client.ipAddr+\":\"+client.port)\n\tif err != nil {\n\t\tlog.Fatal(\"Error during the connection :\", err)\n\t}\n\treturn conn\n}", "func (h *handler) Connect(c *session.Client) {\n\tif c == nil {\n\t\th.logger.Error(LogErrFailedConnect + (ErrClientNotInitialized).Error())\n\t\treturn\n\t}\n\th.logger.Info(fmt.Sprintf(LogInfoConnected, c.ID))\n}", "func (m *RPCModule) connect(host string, port int, user, pass string) util.Map {\n\n\t// Create a client\n\tc := client.NewClient(&types2.Options{\n\t\tHost: host,\n\t\tPort: port,\n\t\tUser: user,\n\t\tPassword: pass,\n\t})\n\n\t// Create a RPC context\n\tctx := m.ClientContextMaker(c)\n\n\t// Add call function for raw calls\n\tctx.Objects[\"call\"] = ctx.call\n\n\t// Attempt to query the methods from the RPC server.\n\t// Panics if not successful.\n\tmethods := ctx.call(\"rpc_methods\")\n\n\t// Build RPC namespaces and add methods into them\n\tfor _, method := range methods[\"methods\"].([]interface{}) {\n\t\to := objx.New(method)\n\t\tnamespace := o.Get(\"namespace\").String()\n\t\tname := o.Get(\"name\").String()\n\t\tnsObj, ok := ctx.Objects[namespace]\n\t\tif !ok {\n\t\t\tnsObj = make(map[string]interface{})\n\t\t\tctx.Objects[namespace] = nsObj\n\t\t}\n\t\tnsObj.(map[string]interface{})[name] = func(params ...interface{}) interface{} {\n\t\t\treturn ctx.call(fmt.Sprintf(\"%s_%s\", namespace, name), params...)\n\t\t}\n\t}\n\n\treturn ctx.Objects\n}", "func (this Scanner) connect(user, host string, conf ssh.ClientConfig) (*ssh.Client, *ssh.Session, error) {\n\t// Develop the network connection out\n\tconn, err := ssh.Dial(\"tcp\", host, &conf)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// Actually perform our connection\n\tsession, err := conn.NewSession()\n\tif err != nil {\n\t\tconn.Close()\n\t\treturn nil, nil, err\n\t}\n\n\treturn conn, session, nil\n}", "func doConnect(qmName string) error {\n\n\t// Set connection configuration\n\tvar connConfig mqmetric.ConnectionConfig\n\tconnConfig.ClientMode = false\n\tconnConfig.UserId = \"\"\n\tconnConfig.Password = \"\"\n\n\t// Connect to the queue manager - open the command and dynamic reply queues\n\terr := mqmetric.InitConnectionStats(qmName, \"SYSTEM.DEFAULT.MODEL.QUEUE\", \"\", &connConfig)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to connect to queue manager %s: %v\", qmName, err)\n\t}\n\n\t// Discover available metrics for the queue manager and subscribe to them\n\terr = mqmetric.DiscoverAndSubscribe(\"\", true, \"\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to discover and subscribe to metrics: %v\", err)\n\t}\n\n\treturn nil\n}", "func (b *broker) connect() error {\n\tvar err error\n\turi := fmt.Sprintf(\n\t\t\"%v://%v:%v@%v:%v/\",\n\t\tb.Scheme,\n\t\tb.User,\n\t\tb.Pass,\n\t\tb.Host,\n\t\tb.Port,\n\t)\n\tif b.connection, err = amqp.Dial(uri); err != nil {\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"url\": uri,\n\t\t\t\"error\": err,\n\t\t}).Warn(\"error while dialling AMQP broker\")\n\t\treturn errors.Wrap(err, \"while dialling AMQP broker\")\n\t}\n\tif b.achannel, err = b.connection.Channel(); err != nil {\n\t\treturn errors.Wrap(err, \"could not open AMQP channel\")\n\t}\n\t// Best practice for AMQP is to unconditionally declare the exchange on connection\n\tif err = b.achannel.ExchangeDeclare(\n\t\tb.Exchange, // name of the exchange\n\t\t\"topic\", // type is always topic\n\t\ttrue, // durable\n\t\tfalse, // delete when complete\n\t\tfalse, // internal\n\t\tfalse, // noWait\n\t\tnil, // arguments\n\t); err != nil {\n\t\treturn errors.Wrap(err, \"could not declare AMQP exchange\")\n\t}\n\tb.closed = make(chan *amqp.Error)\n\tb.achannel.NotifyClose(b.closed)\n\n\treturn nil\n}", "func connect() (connection mysql.Conn) {\n\tuser := \"root\"\n\tpass := \"toor\"\n\tdbname := \"trackerdb\"\n\tproto := \"tcp\"\n\taddr := \"127.0.0.1:3306\"\n\n\tdb := mysql.New(proto, \"\", addr, user, pass, dbname)\n\n\terr := db.Connect()\n\tif err != nil {\n\t\tfmt.Println(\"Database Connection Error:\", err)\n\t}\n\n\treturn db\n}", "func (c *Client) Connect() error {\n\t//c.handlers = make(map[string]func(Event))\n\t//c.respQ = make(chan map[string]interface{}, bufferSize)\n\n\tconn, err := connectWS(c.Host, c.Port)\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.Conn = conn\n\n\tglobal.LOG.Info(\"logged in (authentication successful)\")\n\tc.connected = true\n\treturn nil\n}", "func (c *Driver) Connect() error {\n\tif !IsChannelValid(c.channel) {\n\t\treturn InvalidChanName\n\t}\n\n\tc.clean()\n\tconn, err := net.Dial(\"tcp\", fmt.Sprintf(\"%s:%d\", c.Host, c.Port))\n\tif err != nil {\n\t\treturn err\n\t} \n\t\n\tc.closed = false\n\tc.conn = conn\n\tc.reader = bufio.NewReader(c.conn)\n\n\terr = c.write(fmt.Sprintf(\"START %s %s\", c.channel, c.Password))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = c.read()\n\t_, err = c.read()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func on_connect(c net.Conn) {\n conn := create_connection(c)\n connected_clients_mutex.Lock()\n conn_id, _ := strconv.Atoi(conn.id)\n connected_clients[conn_id] = conn\n connected_clients_mutex.Unlock()\n handle_conn(conn)\n}", "func (s *bookingServiceServer) connect(ctx context.Context) (*sql.Conn, error) {\n\tc, err := s.db.Conn(ctx)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Unknown, \"failed to connect to database-> \"+err.Error())\n\t}\n\treturn c, nil\n}", "func (l *Lock) Connect(ctx context.Context) (err error) {\n\tl.logger.Debug(\"node %s connecting to consul lock %s\", l.id, l.config.Consul.Address)\n\tif l.client != nil {\n\t\treturn fmt.Errorf(\"node %s already connected\", l.id)\n\t}\n\n\tl.client, err = consul.NewClient(l.config.Consul)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (i *IrcClient) Connect(uri string, sslCert string, sslKey string) {\n\tlog(\"IRC connect - connecting to \" + uri)\n\n\ti.Outgoing = make(chan []byte, 100)\n\t\n\tvar err error\n\tcert, err := tls.LoadX509KeyPair(sslCert, sslKey)\n\tif err != nil {\n\t\tlog(\"IRC connect - error loading X509 Key Pair\")\n\t\tlog(err.Error())\n\t\treturn\n\t}\n\n config := tls.Config{Certificates: []tls.Certificate{cert}, InsecureSkipVerify: true}\n\ti.Conn, err = tls.Dial(\"tcp\", uri, &config)\n\n\tif err != nil {\n\t\tlog(\"IRC connect - error connecting to \" + uri)\n\t\tlog(err.Error())\n\t\treturn \n\t}\n\n\ti.Connected = true\n\n\tlog(\"IRC connect - connection successful to \" + uri + \" \" + i.Conn.RemoteAddr().String())\n}", "func (r *Rmq) Connect() {\n\tconn, err := amqp.Dial(r.uri)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tr.conn = conn\n\n\tch, err := conn.Channel()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tr.ch = ch\n}", "func (c *CommunicationClient) Connect() error{\r\n\r\n if c.conn != nil{\r\n if c.conn.IsClosed() {\r\n conn, err := amqp.Dial(c.host)\r\n\r\n if err != nil {\r\n return err\r\n }\r\n\r\n ch, err := conn.Channel()\r\n\r\n if err != nil {\r\n return err\r\n }\r\n\r\n c.conn = conn\r\n c.ch = ch\r\n\r\n return nil\r\n }else{\r\n\r\n ch, err := c.conn.Channel()\r\n\r\n if err != nil {\r\n return err\r\n }\r\n\r\n c.ch = ch\r\n\r\n return nil\r\n }\r\n }else{\r\n conn, err := amqp.Dial(c.host)\r\n\r\n if err != nil {\r\n return err\r\n }\r\n\r\n ch, err := conn.Channel()\r\n\r\n if err != nil {\r\n return err\r\n }\r\n\r\n c.conn = conn\r\n c.ch = ch\r\n\r\n return nil\r\n }\r\n\r\n\r\n}", "func (s *Server) Connect() {\n\tconnectionAddr := fmt.Sprintf(\"amqp://%s:%s@%s\", s.RabbitMQUsername, s.RabbitMQPassword, s.RabbitMQHost)\n\tconn, err := amqp.Dial(connectionAddr)\n\tFailOnError(err, \"Failed to connect to RabbitMQ\")\n\ts.Conn = conn\n}", "func (c *client) connect() error {\n\tvar connection *sql.DB\n\tvar err error\n\tif os.Getenv(\"MODE\") == \"development\" {\n\t\tvar connectionString = fmt.Sprintf(\n\t\t\t\"host=%s port=%s user=%s password=%s dbname=%s sslmode=disable\",\n\t\t\tos.Getenv(\"PGHOST\"),\n\t\t\tos.Getenv(\"PGPORT\"),\n\t\t\tos.Getenv(\"PGUSER\"),\n\t\t\tos.Getenv(\"PGPASSWORD\"),\n\t\t\tos.Getenv(\"PGDATABASE\"),\n\t\t)\n\t\tc.connectionString = connectionString\n\t\tconnection, err = sql.Open(\"postgres\", connectionString)\n\t} else if os.Getenv(\"MODE\") == \"production\" {\n\t\tconnection, err = sql.Open(\"postgres\", os.Getenv(\"DATABASE_URL\"))\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"connection to pg failed: %v\", err)\n\t}\n\n\tc.db = connection\n\n\tfmt.Println(\"postgres connection established...\")\n\treturn nil\n}", "func (r *Runtime) Connect(ta TaskAssigner) (e error) {\n\tif r.isConnected {\n\t\te = errors.New(\"Already allocated worker\")\n\t\treturn\n\t}\n\n\tr.isConnected = true\n\tr.taskAssigner = ta\n\n\treturn\n}", "func ExampleConnect() {\n\terrChan := make(chan error)\n\n\topts := &Options{\n\t\tUsername: \"username\",\n\t\tPassword: \"password\",\n\t}\n\n\t// connect to the server\n\tconn, err := Connect(\"ws://localhost:9191/channel\", opts, errChan)\n\tif err != nil {\n\t\tlog.Printf(\"connect failed: %s\", err)\n\t\treturn\n\t}\n\n\t// disconnect from the server when done with the connection\n\tdefer conn.Disconnect()\n\n\t// listen for asynnchronous errors\n\tgo func() {\n\t\tfor err := range errChan {\n\t\t\tlog.Printf(\"connection error: %s\", err)\n\t\t}\n\t}()\n\t// Output:\n}", "func (s *Realm) OnConnect(c *connection.Connection) {\r\n\tslog.Printf(\"New Connection from: %s\\n\", c.PeerAddr())\r\n\r\n\tsess := &RealmSession{\r\n\t\tConn: c,\r\n\t\tStartTime: time.Now(),\r\n\t}\r\n\r\n\ts.mtx.Lock()\r\n\te := s.conns.PushBack(sess)\r\n\ts.mtx.Unlock()\r\n\tc.SetContext(e)\r\n\r\n\tc.Send([]byte(\"fvpvTbKVC\\\\WnpqQvh_xdY\\\\\\\\\"))\r\n}", "func (tg *TradesGroup) connect() {\n\ttg.wsClient = websocket.NewClient(wsURL, tg.httpProxy)\n\tif err := tg.wsClient.Connect(); err != nil {\n\t\tlog.Println(\"[BITFINEX] Error connecting to bitfinex API: \", err)\n\t\treturn\n\t}\n\ttg.wsClient.Listen(tg.bus.dch, tg.bus.ech)\n}", "func (metrics *Metrics) Connect() error {\n\t// Make sure the connection isn't open\n\tif metrics.conn != nil {\n\t\t_ = metrics.conn.Close()\n\t}\n\t// Prepare connection string\n\tconnString := fmt.Sprintf(\"%s:%d\", metrics.Host, metrics.Port)\n\t// Check timeout\n\tif metrics.Timeout == 0 {\n\t\tmetrics.Timeout = defaultTimeout * time.Second\n\t}\n\tvar err error\n\tvar conn net.Conn\n\tvar udpAddr *net.UDPAddr\n\t// Establish connection by type\n\tif metrics.Protocol == \"udp\" {\n\t\tudpAddr, err = net.ResolveUDPAddr(\"udp\", connString)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tconn, err = net.DialUDP(metrics.Protocol, nil, udpAddr)\n\t} else {\n\t\tconn, err = net.DialTimeout(metrics.Protocol, connString, metrics.Timeout)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tmetrics.conn = conn\n\n\treturn nil\n}" ]
[ "0.67077905", "0.6634654", "0.6631335", "0.65912145", "0.6491219", "0.64541703", "0.64315164", "0.6377671", "0.6353071", "0.63220286", "0.6295981", "0.62878853", "0.626565", "0.6226095", "0.6194442", "0.6186907", "0.6164935", "0.6159773", "0.61356914", "0.6104107", "0.61007744", "0.6068302", "0.603995", "0.60278696", "0.60051", "0.5998215", "0.5992943", "0.59671515", "0.59588516", "0.5957083", "0.5942206", "0.5936303", "0.59344125", "0.59227145", "0.5921486", "0.5911093", "0.5904933", "0.590149", "0.5899057", "0.58863455", "0.58858293", "0.58787376", "0.58680916", "0.5862187", "0.5862025", "0.5856846", "0.5850692", "0.5844529", "0.58437955", "0.58320504", "0.58240944", "0.5814951", "0.57989436", "0.57944036", "0.5790564", "0.5779234", "0.5769868", "0.5753728", "0.57514966", "0.5745133", "0.57359046", "0.57336456", "0.5708663", "0.5706979", "0.57029796", "0.5702311", "0.569683", "0.5693575", "0.5691396", "0.56771964", "0.56662804", "0.56610626", "0.5660661", "0.5657735", "0.5656118", "0.5651937", "0.56512475", "0.5645267", "0.5642474", "0.56396514", "0.56363964", "0.56362575", "0.56346434", "0.56323576", "0.56299764", "0.5627739", "0.56276566", "0.5619894", "0.5613247", "0.5612177", "0.5604068", "0.56025994", "0.560107", "0.559706", "0.55924183", "0.55908036", "0.5580322", "0.55776775", "0.5571728", "0.55670136" ]
0.7555079
0
NewServer creates and starts a new server that listens for spans and annotations on l and adds them to the collector c. Call the CollectorServer's Start method to start listening and serving.
NewServer создает и запускает новый сервер, который слушает спаны и аннотации на l и добавляет их в сборщик c. Вызовите метод Start у CollectorServer, чтобы начать прослушивание и обслуживание.
func NewServer(l net.Listener, c Collector) *CollectorServer { cs := &CollectorServer{c: c, l: l} return cs }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewServer(cfg config.Config, ll *log.Logger) *Server {\n\tif ll == nil {\n\t\tll = log.New(ioutil.Discard, \"\", 0)\n\t}\n\n\t// Set up Prometheus instrumentation using the typical Go collectors.\n\treg := prometheus.NewPedanticRegistry()\n\treg.MustRegister(\n\t\tprometheus.NewGoCollector(),\n\t\tprometheus.NewProcessCollector(prometheus.ProcessCollectorOpts{}),\n\t\tnewInterfaceCollector(cfg.Interfaces),\n\t)\n\n\treturn &Server{\n\t\tcfg: cfg,\n\n\t\tll: ll,\n\t\treg: reg,\n\n\t\tready: make(chan struct{}),\n\t}\n}", "func NewServer(l Listener) *server {\n\treturn &server{\n\t\tlistener: l,\n\t}\n}", "func newServer(sc *ServerConfig, b backends.Backend, l log.Logger) (*server, error) {\n\tserver := &server{\n\t\tclientPool: NewPool(sc.MaxClients),\n\t\tclosedListener: make(chan bool, 1),\n\t\tlistenInterface: sc.ListenInterface,\n\t\tstate: ServerStateNew,\n\t\tenvelopePool: mail.NewPool(sc.MaxClients),\n\t}\n\tserver.logStore.Store(l)\n\tserver.backendStore.Store(b)\n\tlogFile := sc.LogFile\n\tif logFile == \"\" {\n\t\t// none set, use the same log file as mainlog\n\t\tlogFile = server.mainlog().GetLogDest()\n\t}\n\t// set level to same level as mainlog level\n\tmainlog, logOpenError := log.GetLogger(logFile, server.mainlog().GetLevel())\n\tserver.mainlogStore.Store(mainlog)\n\tif logOpenError != nil {\n\t\tserver.log().WithError(logOpenError).Errorf(\"Failed creating a logger for server [%s]\", sc.ListenInterface)\n\t}\n\n\tserver.setConfig(sc)\n\tserver.setTimeout(sc.Timeout)\n\tif err := server.configureSSL(); err != nil {\n\t\treturn server, err\n\t}\n\treturn server, nil\n}", "func NewServer() *Server {}", "func NewServer(cfg config.HTTP, staticResource bool, r *linmetric.Registry) Server {\n\ts := &server{\n\t\tcfg: cfg,\n\t\taddr: fmt.Sprintf(\":%d\", cfg.Port),\n\t\tgin: gin.New(),\n\t\tstaticResource: staticResource,\n\t\tserver: http.Server{\n\t\t\t// use extra timeout for ingestion and query timeout\n\t\t\t// if write timeout will return ERR_EMPTY_RESPONSE, chrome will does auto retry.\n\t\t\t// https://www.bennadel.com/blog/3257-google-chrome-will-automatically-retry-requests-on-certain-error-responses.htm\n\t\t\t// https://mariocarrion.com/2021/09/17/golang-software-architecture-resilience-http-servers.html\n\t\t\t// WriteTimeout: cfg.WriteTimeout.Duration(),\n\t\t\tReadTimeout: cfg.ReadTimeout.Duration(),\n\t\t\tIdleTimeout: cfg.IdleTimeout.Duration(),\n\t\t},\n\t\tr: r,\n\t\tlogger: logger.GetLogger(\"HTTP\", \"Server\"),\n\t}\n\ts.init()\n\treturn s\n}", "func NewCollectServer(cfg *ServerConfig) *CollectServer {\n\tserver := &CollectServer{Config: cfg}\n\tlogger := logrus.New()\n\tlogger.Out = cfg.LogCfg.Output\n\tlogger.Level = cfg.LogCfg.Level\n\tlogger.Formatter = cfg.LogCfg.Format\n\tserver.Logger = logger\n\treturn server\n}", "func newServer() *traceServer {\n\treturn &traceServer{\n\t\tevents: make(map[string]*trace.Trace),\n\t}\n}", "func NewServer(h *Handlers, limits *Limits, l net.Listener) *Server {\n\treturn &Server{Handlers: h, Limits: limits, Listener: l}\n}", "func New(listener net.Listener, httpServer *http.Server) goroutine.BackgroundRoutine {\n\treturn &server{\n\t\tserver: httpServer,\n\t\tmakeListener: func() (net.Listener, error) { return listener, nil },\n\t}\n}", "func NewServer(authFunc, cmdFunc func(io.ReadWriter, []byte) error) (*Server, error) {\n\tvar err error\n\ts := new(Server)\n\ts.ln, err = nettest.NewLocalListener(\"tcp\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgo s.serve(authFunc, cmdFunc)\n\treturn s, nil\n}", "func NewServer(entries ...EntryPoint) *Server {\n\treturn &Server{\n\t\tentrypoints: entries,\n\t\tstopChan: make(chan bool, 1),\n\t}\n}", "func NewServer(config domain.ServerConfig) *Server {\n\tdebugger := logger.New(log.New(ioutil.Discard, \"\", 0))\n\tif config.Debug {\n\t\tdebugger = logger.New(log.New(os.Stderr, \"[debug] \", log.Flags()|log.Lshortfile))\n\t}\n\n\tdb, err := bolt.Open(config.BoltPath, 0644, nil)\n\tif err != nil {\n\t\tlog.Fatal(\"failed to start bolt db\")\n\t}\n\tdefer db.Close()\n\n\ts := &Server{\n\t\tConfig: config,\n\t\ti: uc.NewInteractor(\n\t\t\tconfig,\n\t\t\tcookies.New(config.CookieAge),\n\t\t\tdebugger,\n\t\t\tresources.New(encoder.New()),\n\t\t\thttpCaller.New(),\n\t\t\tmail.New(domain.EmailConfig{}),\n\t\t\tpathInfo.New(config),\n\t\t\tencoder.New(),\n\t\t\tsparql.New(),\n\t\t\tpages.New(config.DataRoot),\n\t\t\ttokenStorer.New(db),\n\t\t\tdomain.URIHandler{},\n\t\t\tuuid.New(),\n\t\t\tauthentication.New(httpCaller.New()),\n\t\t\tspkac.New(),\n\t\t),\n\t\tlogger: debugger,\n\t\tcookieManager: cookies.New(config.CookieAge),\n\t\tpathInformer: pathInfo.New(config),\n\t\turiManipulator: domain.URIHandler{},\n\t}\n\n\tmime.AddRDFExtension(s.Config.ACLSuffix)\n\tmime.AddRDFExtension(s.Config.MetaSuffix)\n\n\ts.logger.Debug(\"---- starting server ----\")\n\ts.logger.Debug(\"config: %#v\\n\", s.Config)\n\treturn s\n}", "func newServer(ctx context.Context, logger zerolog.Logger, dsn datastore.PGDatasourceName) (*server.Server, func(), error) {\n\t// This will be filled in by Wire with providers from the provider sets in\n\t// wire.Build.\n\twire.Build(\n\t\twire.InterfaceValue(new(trace.Exporter), trace.Exporter(nil)),\n\t\tgoCloudServerSet,\n\t\tapplicationSet,\n\t\tappHealthChecks,\n\t\twire.Struct(new(server.Options), \"HealthChecks\", \"TraceExporter\", \"DefaultSamplingPolicy\", \"Driver\"),\n\t\tdatastore.NewDB,\n\t\twire.Bind(new(datastore.Datastorer), new(*datastore.Datastore)),\n\t\tdatastore.NewDatastore)\n\treturn nil, nil, nil\n}", "func New(addr string, host app.HostService, collector *metrics.Collector) app.Server {\n\treturn &server{\n\t\tsrv: telnet.Server{Addr: addr, Handler: nil},\n\t\thost: host,\n\t\tcollector: collector,\n\t}\n}", "func NewServer(listen string, port int, metrics bool) (*Server, error) {\n\n\tr := gin.Default()\n\tif metrics {\n\t\tp := ginprom.New(\n\t\t\tginprom.Engine(r),\n\t\t\tginprom.Subsystem(\"gin\"),\n\t\t\tginprom.Path(\"/metrics\"),\n\t\t)\n\t\tr.Use(p.Instrument())\n\t}\n\n\ts := &Server{\n\t\trouter: r,\n\t\tport: port,\n\t\tlisten: listen,\n\t}\n\ts.routes()\n\treturn s, nil\n}", "func NewServer(c Configuration, b *builder.Builder, stg astichat.Storage) *Server {\n\tastilog.Debug(\"Starting server\")\n\treturn &Server{\n\t\tchannelQuit: make(chan bool),\n\t\tserverHTTP: NewServerHTTP(c.Addr.HTTP, c.PathStatic, b, stg),\n\t\tserverUDP: NewServerUDP(stg),\n\t\tstartedAt: time.Now(),\n\t}\n}", "func NewServer(\n\tconf *config.ChaosDashboardConfig,\n\texperimentArchive core.ExperimentStore,\n\tscheduleArchive core.ScheduleStore,\n\tevent core.EventStore,\n\tworkflowStore core.WorkflowStore,\n\tlogger logr.Logger,\n) (*Server, client.Client, client.Reader, *runtime.Scheme) {\n\ts := &Server{logger: logger}\n\n\t// namespace scoped\n\toptions := ctrl.Options{\n\t\tScheme: scheme,\n\t\tMetricsBindAddress: net.JoinHostPort(conf.MetricHost, strconv.Itoa(conf.MetricPort)),\n\t\tLeaderElection: conf.EnableLeaderElection,\n\t\tPort: 9443,\n\t}\n\tif conf.ClusterScoped {\n\t\tlogger.Info(\"Chaos controller manager is running in cluster scoped mode.\")\n\t} else {\n\t\tlogger.Info(\"Chaos controller manager is running in namespace scoped mode.\", \"targetNamespace\", conf.TargetNamespace)\n\t\toptions.Namespace = conf.TargetNamespace\n\t}\n\n\tvar err error\n\n\tcfg := ctrl.GetConfigOrDie()\n\n\tif conf.QPS > 0 {\n\t\tcfg.QPS = conf.QPS\n\t\tcfg.Burst = conf.Burst\n\t}\n\n\ts.Manager, err = ctrl.NewManager(cfg, options)\n\tif err != nil {\n\t\tlogger.Error(err, \"unable to start collector\")\n\t\tos.Exit(1)\n\t}\n\n\tif conf.SecurityMode {\n\t\tclientpool.K8sClients, err = clientpool.NewClientPool(cfg, scheme, 100)\n\t\tif err != nil {\n\t\t\t// this should never happen\n\t\t\tlogger.Error(err, \"fail to create client pool\")\n\t\t\tos.Exit(1)\n\t\t}\n\t} else {\n\t\tclientpool.K8sClients, err = clientpool.NewLocalClient(cfg, scheme)\n\t\tif err != nil {\n\t\t\tlogger.Error(err, \"fail to create client pool\")\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n\n\tfor kind, chaosKind := range v1alpha1.AllKinds() {\n\t\tif err = (&ChaosCollector{\n\t\t\tClient: s.Manager.GetClient(),\n\t\t\tLog: logger.WithName(kind),\n\t\t\tarchive: experimentArchive,\n\t\t\tevent: event,\n\t\t}).Setup(s.Manager, chaosKind.SpawnObject()); err != nil {\n\t\t\tlogger.Error(err, \"unable to create collector\", \"collector\", kind)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n\n\tif err = (&ScheduleCollector{\n\t\tClient: s.Manager.GetClient(),\n\t\tLog: logger.WithName(\"schedule-collector\").WithName(v1alpha1.KindSchedule),\n\t\tarchive: scheduleArchive,\n\t}).Setup(s.Manager, &v1alpha1.Schedule{}); err != nil {\n\t\tlogger.Error(err, \"unable to create collector\", \"collector\", v1alpha1.KindSchedule)\n\t\tos.Exit(1)\n\t}\n\n\tif err = (&EventCollector{\n\t\tClient: s.Manager.GetClient(),\n\t\tLog: logger.WithName(\"event-collector\").WithName(\"Event\"),\n\t\tevent: event,\n\t}).Setup(s.Manager, &v1.Event{}); err != nil {\n\t\tlogger.Error(err, \"unable to create collector\", \"collector\", v1alpha1.KindSchedule)\n\t\tos.Exit(1)\n\t}\n\n\tif err = (&WorkflowCollector{\n\t\tkubeClient: s.Manager.GetClient(),\n\t\tLog: logger.WithName(\"workflow-collector\").WithName(v1alpha1.KindWorkflow),\n\t\tstore: workflowStore,\n\t}).Setup(s.Manager, &v1alpha1.Workflow{}); err != nil {\n\t\tlogger.Error(err, \"unable to create collector\", \"collector\", v1alpha1.KindWorkflow)\n\t\tos.Exit(1)\n\t}\n\n\treturn s, s.Manager.GetClient(), s.Manager.GetAPIReader(), s.Manager.GetScheme()\n}", "func NewServer(ctx context.Context, config cache.Cache, callbacks xdsv3.Callbacks) Server {\n\t// Delta server is not used. Hence the envoy default implementation is used.\n\treturn NewServerAdvanced(rest.NewServer(config, callbacks), sotw.NewServer(ctx, config, callbacks), envoy_delta.NewServer(ctx, config, callbacks))\n}", "func NewServer(opts Opts) (net.Listener, *grpc.Server) {\n\tlis, err := net.Listen(\"tcp\", fmt.Sprintf(\"%s:%d\", opts.Host, opts.Port))\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to listen on %s:%d: %v\", opts.Host, opts.Port, err)\n\t}\n\tlog.Notice(\"Listening on %s:%d\", opts.Host, opts.Port)\n\n\ts := grpc.NewServer(OptionalTLS(opts.KeyFile, opts.CertFile, opts.TLSMinVersion,\n\t\tgrpc.ChainUnaryInterceptor(append([]grpc.UnaryServerInterceptor{\n\t\t\tLogUnaryRequests,\n\t\t\tserverMetrics.UnaryServerInterceptor(),\n\t\t\tgrpc_recovery.UnaryServerInterceptor(),\n\t\t}, unaryAuthInterceptor(opts)...)...),\n\t\tgrpc.ChainStreamInterceptor(append([]grpc.StreamServerInterceptor{\n\t\t\tLogStreamRequests,\n\t\t\tserverMetrics.StreamServerInterceptor(),\n\t\t\tgrpc_recovery.StreamServerInterceptor(),\n\t\t}, streamAuthInterceptor(opts)...)...),\n\t\tgrpc.MaxRecvMsgSize(419430400), // 400MB\n\t\tgrpc.MaxSendMsgSize(419430400),\n\t)...)\n\n\tserverMetrics.InitializeMetrics(s)\n\treflection.Register(s)\n\tif !opts.NoHealth {\n\t\tgrpc_health_v1.RegisterHealthServer(s, health.NewServer())\n\t}\n\treturn lis, s\n}", "func New(\n\tserverID string,\n\ttracer *zipkin.Tracer,\n\tfS fetching.Service,\n\taS adding.Service,\n\tmS modifying.Service,\n\trS removing.Service,\n) Server {\n\ta := &server{\n\t\tserverID: serverID,\n\t\ttracer: tracer,\n\t\tfetching: fS,\n\t\tadding: aS,\n\t\tmodifying: mS,\n\t\tremoving: rS}\n\trouter(a)\n\n\treturn a\n}", "func New(\n\tserverID string,\n\ttracer *zipkin.Tracer,\n\tfS fetching.Service,\n\taS adding.Service,\n\tmS modifying.Service,\n\trS removing.Service,\n) Server {\n\ta := &server{\n\t\tserverID: serverID,\n\t\ttracer: tracer,\n\t\tfetching: fS,\n\t\tadding: aS,\n\t\tmodifying: mS,\n\t\tremoving: rS}\n\trouter(a)\n\n\treturn a\n}", "func NewServer() *server {\n\ts := &server{\n\t\tstore: make(map[string]*string),\n\t\tops: make(chan func()),\n\t}\n\tgo s.loop()\n\treturn s\n}", "func newServer(handler connHandler, logger *zap.Logger) *server {\n\ts := &server{\n\t\thandler: handler,\n\t\tlogger: logger.With(zap.String(\"sector\", \"server\")),\n\t}\n\treturn s\n}", "func newServer(deps dependencies) Component {\n\treturn newServerCompat(deps.Config, deps.Log, deps.Replay, deps.Debug, deps.Params.Serverless)\n}", "func NewServer(stop chan bool) *Server {\n\tmux := http.NewServeMux()\n\ttotalTimeChan := make(chan time.Duration, 100)\n\tstatsRequestChan := make(chan int, 100)\n\tincomingStatsChan := make(chan Stats, 100)\n\tmgr := managerChannels{\n\t\ttotalTimeChan: totalTimeChan,\n\t\tstatsRequestChan: statsRequestChan,\n\t\tincomingStatsChan: incomingStatsChan,\n\t\tstop: stop,\n\t}\n\ts := &Server{\n\t\ttotaltime: totalTimeChan,\n\t\tstatsrequest: statsRequestChan,\n\t\tincomingstats: incomingStatsChan,\n\t\tstop: stop,\n\t\tmux: mux,\n\t}\n\n\tgo computeStats(mgr)\n\ts.mux.HandleFunc(\"/hash\", s.computePasswordHash)\n\ts.mux.HandleFunc(\"/shutdown\", func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method == \"GET\" {\n\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\tstop <- true\n\t\t} else {\n\t\t\tw.WriteHeader(http.StatusNotFound)\n\t\t}\n\t})\n\ts.mux.HandleFunc(\"/stats\", s.getStats)\n\treturn s\n}", "func newServer(ctx common.Context, self *replica, listener net.Listener, workers int) (net.Server, error) {\n\tserver := &rpcServer{ctx: ctx, logger: ctx.Logger(), self: self}\n\treturn net.NewServer(ctx, listener, serverInitHandler(server), workers)\n}", "func NewServer(config *ClusterConfig, store mcmodel.MCConfigStore) (*Server, error) {\n\trouter := mux.NewRouter()\n\ts := &Server{\n\t\thttpServer: http.Server{\n\t\t\tReadTimeout: 10 * time.Second,\n\t\t\tWriteTimeout: 10 * time.Second,\n\t\t\tAddr: fmt.Sprintf(\":%d\", config.AgentPort),\n\t\t\tHandler: router,\n\t\t},\n\t\tstore: store,\n\t\tconfig: config,\n\t}\n\t_ = router.NewRoute().PathPrefix(\"/exposed/{clusterID}\").Methods(\"GET\").HandlerFunc(s.handlePoliciesReq)\n\n\treturn s, nil\n}", "func NewServer(id uuid.UUID, csrv *conf.Service, c *conf.Server, logger log.Logger, r *etcd.Registry) (*Server, error) {\n\tlogicClient, err := logic.NewClient(context.Background(), grpc.WithDiscovery(r))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts := &Server{\n\t\tc: c,\n\t\tuuid: id.String(),\n\t\tround: NewRound(c),\n\t\trpcClient: logicClient,\n\t}\n\t// init bucket\n\ts.buckets = make([]*Bucket, c.Bucket.Size)\n\ts.bucketIdx = uint32(c.Bucket.Size)\n\tfor i := int32(0); i < c.Bucket.Size; i++ {\n\t\ts.buckets[i] = NewBucket(c.Bucket)\n\t}\n\ts.serverID = ip.InternalIP()\n\tgo s.onlineproc()\n\n\tif err := InitWhitelist(c.Whitelist, logger); err != nil {\n\t\tpanic(err)\n\t}\n\tif err := InitTCP(logger, s, c.Tcp.Bind, runtime.NumCPU()); err != nil {\n\t\tpanic(err)\n\t}\n\tif err := InitWebsocket(logger, s, c.Websocket.Bind, runtime.NumCPU()); err != nil {\n\t\tpanic(err)\n\t}\n\t// if conf.Conf.Websocket.TLSOpen {\n\t// \tif err := comet.InitWebsocketWithTLS(srv, conf.Conf.Websocket.TLSBind, conf.Conf.Websocket.CertFile, conf.Conf.Websocket.PrivateFile, runtime.NumCPU()); err != nil {\n\t// \t\tpanic(err)\n\t// \t}\n\t// }\n\n\treturn s, nil\n}", "func NewServer() *gin.Engine {\n\tr := gin.Default()\n\n\tsetMetricsCollectors(r)\n\n\tr.GET(\"/ping\", pingHandler)\n\tr.GET(\"/metrics\", gin.WrapH(promhttp.Handler()))\n\n\treturn r\n}", "func NewServer(endpoint string) (*Server, error) {\n\n\tret := &Server{}\n\tvar err error\n\tret.Listener, err = net.Listen(\"tcp\", endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tret.mux = http.NewServeMux()\n\tret.mux.HandleFunc(\"/\", func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Write([]byte(\"This is the monitoring endpoint\"))\n\t})\n\tret.mux.Handle(\"/mon/varz\", expvar.Handler())\n\n\tret.mux.HandleFunc(\"/mon/pprof/\", pprof.Index)\n\tret.mux.HandleFunc(\"/mon/pprof/cmdline\", pprof.Cmdline)\n\tret.mux.HandleFunc(\"/mon/pprof/profile\", pprof.Profile)\n\tret.mux.HandleFunc(\"/mon/pprof/symbol\", pprof.Symbol)\n\tEnableTracing()\n\tret.mux.HandleFunc(\"/mon/trace\", TraceHandler())\n\tret.srv = &http.Server{}\n\treturn ret, nil\n}", "func New(sigs chan os.Signal) *Server {\n\ts := &Server{mux: http.NewServeMux(), sigs: sigs}\n\n\tif s.logger == nil {\n\t\ts.logger = log.New(os.Stdout, \"\", 0)\n\t}\n\n\ts.db = store.NewStore()\n\n\ts.mux.HandleFunc(\"/\", s.latencyMiddleware(s.index))\n\ts.mux.HandleFunc(\"/hash/\", s.latencyMiddleware(s.hash))\n\ts.mux.HandleFunc(\"/shutdown/\", s.latencyMiddleware(s.shutdown))\n\ts.mux.HandleFunc(\"/stats/\", s.stats)\n\n\treturn s\n}", "func NewServer(run func(string, string, *pb.Session) *pipe.Reader,\n\tmodelDir string) *Server {\n\treturn &Server{run: run, modelDir: modelDir}\n}", "func NewServer(conf *config.Config, projectClient project.Client, entriesClient timetracking.Client) *Server {\n\te := echo.New()\n\n\t//recover from panics\n\te.Use(middleware.Recover())\n\t//add a unique id to each request\n\te.Use(middleware.RequestID())\n\t//add request id to the context\n\te.Use(AddRequestIDToContext())\n\t//add a logger to the context\n\te.Use(AddLoggerToContext())\n\t//use custom logger for all requests\n\te.Use(Logger())\n\t//trace rest calls\n\te.Use(Tracing())\n\n\te.Use(Instrumenting())\n\n\te.HideBanner = true\n\te.HidePort = true\n\n\ts := &Server{\n\t\tconf: conf,\n\t\te: e,\n\t\thttpServer: &http.Server{\n\t\t\tAddr: fmt.Sprintf(\":%d\", conf.HTTPPort),\n\t\t\tReadTimeout: 60 * time.Second, // time to read request\n\t\t\tReadHeaderTimeout: 10 * time.Second, // time to read header, low value to cope with malicious behavior\n\t\t\tWriteTimeout: 20 * time.Second, // time write response\n\t\t\tIdleTimeout: 120 * time.Second, // time between keep-alives requests before connection is closed\n\t\t},\n\t}\n\n\th := &handler{\n\t\tentries: entriesClient,\n\t\tprojects: projectClient,\n\t}\n\n\ts.AddRoutes(h)\n\n\t//serve SPA\n\te.Static(\"/\", \"web\")\n\n\treturn s\n}", "func New(fetcherSvc *services.Fetcher, log *logrus.Entry) *Server {\n\treturn &Server{\n\t\tFetcherSvc: fetcherSvc,\n\t\tLog: log,\n\t}\n}", "func NewServer(name string, logger termlog.Logger) *Server {\n\tbroadcast := make(chan string, 50)\n\ts := &Server{\n\t\tname: name,\n\t\tbroadcast: broadcast,\n\t\tconnections: make(map[*websocket.Conn]bool),\n\t\tlogger: logger,\n\t}\n\tgo s.run(broadcast)\n\treturn s\n}", "func New(srv *cmutation.Server) *Server {\n\treturn &Server{srv}\n}", "func NewServer(versionPrefix string, drainCh chan struct{}) *Server {\n\treturn &Server{\n\t\tClusters: xds.NewManager(\"clusters\", versionPrefix, &envoy_config_cluster_v3.Cluster{}, drainCh),\n\t\tEndpoints: xds.NewManager(\"endpoints\", versionPrefix, &envoy_config_endpoint_v3.ClusterLoadAssignment{}, drainCh),\n\t}\n}", "func NewServer(run func(string, *sf.DB) *sf.PipeReader, db *sf.DB) *server {\n\treturn &server{run: run, db: db}\n}", "func NewServer(config Config) (*Server, error) {\n\tserver := &Server{\n\t\tstartTime: time.Now(),\n\t\tConfig: config,\n\t\ttcpServers: []*healthApi.Server{},\n\t\tconnectivity: &healthReport{},\n\t}\n\n\tswaggerSpec, err := loads.Analyzed(healthApi.SwaggerJSON, \"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !config.Passive {\n\t\tcl, err := ciliumPkg.NewClient(config.CiliumURI)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tserver.Client = cl\n\t\tserver.Server = *server.newServer(swaggerSpec, 0)\n\t}\n\tfor port := range PortToPaths {\n\t\tsrv := server.newServer(swaggerSpec, port)\n\t\tserver.tcpServers = append(server.tcpServers, srv)\n\t}\n\n\treturn server, nil\n}", "func NewServer(\n\taddr string,\n\tcontrollerNS string,\n\tidentityTrustDomain string,\n\tenableH2Upgrade bool,\n\tk8sAPI *k8s.API,\n\tshutdown <-chan struct{},\n) *grpc.Server {\n\tlog := logging.WithFields(logging.Fields{\n\t\t\"addr\": addr,\n\t\t\"component\": \"server\",\n\t})\n\tendpoints := watcher.NewEndpointsWatcher(k8sAPI, log)\n\tprofiles := watcher.NewProfileWatcher(k8sAPI, log)\n\ttrafficSplits := watcher.NewTrafficSplitWatcher(k8sAPI, log)\n\n\tsrv := server{\n\t\tendpoints,\n\t\tprofiles,\n\t\ttrafficSplits,\n\t\tenableH2Upgrade,\n\t\tcontrollerNS,\n\t\tidentityTrustDomain,\n\t\tlog,\n\t\tshutdown,\n\t}\n\n\ts := prometheus.NewGrpcServer()\n\t// linkerd2-proxy-api/destination.Destination (proxy-facing)\n\tpb.RegisterDestinationServer(s, &srv)\n\t// controller/discovery.Discovery (controller-facing)\n\tdiscoveryPb.RegisterDiscoveryServer(s, &srv)\n\treturn s\n}", "func NewServer(l net.Listener, reg registry.Cache, ctl *config.Controller, opts ...ServerOption) *Server {\n\to := defaultServerOptions()\n\tfor _, opt := range opts {\n\t\topt(o)\n\t}\n\n\teds := newEndpointDiscoveryServer(reg)\n\tcds := newConfigDiscoveryServer(ctl)\n\tdds := newDependencyDiscoveryServer(ctl)\n\ts := &Server{\n\t\tl: l,\n\t\toptions: o,\n\t\teds: eds,\n\t\tcds: cds,\n\t\tdds: dds,\n\t}\n\n\tg := grpc.NewServer(s.grpcOptions()...)\n\tapi.RegisterDiscoveryServiceServer(g, s)\n\ts.g = g\n\treturn s\n}", "func NewServer(logger logr.Logger, config *Config) (*Server, error) {\n\tmux := http.NewServeMux()\n\t// Create the tls config\n\ttlsConfig, err := CreateTLSConfig(config.TLSConfig)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not create tls configuration\")\n\t}\n\n\t// Create the http server\n\tdecorated := &http.Server{\n\t\tAddr: config.Addr,\n\t\tHandler: mux,\n\t\tTLSConfig: tlsConfig,\n\t\tReadTimeout: config.ReadTimeout,\n\t\tReadHeaderTimeout: config.ReadHeaderTimeout,\n\t\tWriteTimeout: config.WriteTimeout,\n\t\tIdleTimeout: config.IdleTimeout,\n\t\tMaxHeaderBytes: config.MaxHeaderBytes,\n\t}\n\n\t// Add prometheus Metrics and healthz\n\tpromRegistry := prometheus.NewRegistry()\n\tmux.Handle(\"/metrics\", promhttp.HandlerFor(promRegistry, promhttp.HandlerOpts{Registry: promRegistry}))\n\tmux.Handle(\"/healthz\", &healthzHandler{logger})\n\n\tvar listenFn func() error\n\tif config.TLSConfig.PrivateKeyFile != \"\" || config.TLSConfig.PublicKeyFile != \"\" {\n\t\tlistenFn = func() error {\n\t\t\treturn decorated.ListenAndServeTLS(config.TLSConfig.PublicKeyFile, config.TLSConfig.PrivateKeyFile)\n\t\t}\n\t} else {\n\t\tlistenFn = func() error {\n\t\t\treturn decorated.ListenAndServe()\n\t\t}\n\t}\n\n\treturn &Server{\n\t\tServer: decorated,\n\t\tServeMux: mux,\n\t\tlogger: logger,\n\t\tMetrics: &metricsRegistryImpl{\n\t\t\tMetricsRegistry: metering.NewRegistry(promRegistry), namespace: config.ServerNamespace,\n\t\t},\n\t\tlistenFn: listenFn,\n\t}, nil\n}", "func NewServer(config *ServerConfig) (*Server, errors.Error) {\n\tengine := gin.New()\n\tserver := &Server{*config, engine, nil, make(map[string]Service, 0)}\n\n\t// global middlewares\n\tengine.Use(ginLogger)\n\n\t// metrics\n\tp := ginprometheus.NewPrometheus(config.SubSystemName)\n\tp.ReqCntURLLabelMappingFn = func(c *gin.Context) string {\n\t\turl := c.Request.URL.String()\n\t\tfor _, p := range c.Params {\n\t\t\tif p.Key == \"id\" {\n\t\t\t\turl = strings.Replace(url, p.Value, \":id\", 1)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\treturn url\n\t}\n\tp.Use(engine)\n\n\t// server specific routes\n\tengine.GET(\"/healthz\", server.handleGetHealthz)\n\tengine.GET(\"/readiness\", server.handleGetReadiness)\n\n\treturn server, nil\n}", "func NewServer(port int, params *Params) (Server, error) {\n\tstr := lspnet.JoinHostPort(\"localhost\", strconv.Itoa(port))\n\tln, err := lspnet.ResolveUDPAddr(\"udp\", str)\n\tif err != nil {\n\t\tfmt.Println(\"resolving error\")\n\t\treturn nil, err\n\t}\n\tconn, err := lspnet.ListenUDP(\"udp\", ln)\n\tif err != nil {\n\t\tfmt.Println(\"listening error\")\n\t\treturn nil, err\n\t}\n\tepoch_interval = params.EpochMillis\n\tepoch_limit = params.EpochLimit\n\twindow_size = params.WindowSize\n\tmaxBackOffInterval = params.MaxBackOffInterval\n\tserver := &server{\n\t\t// server listening port\n\t\tln: conn,\n\t\t// all clients\n\t\tclients: make(map[int]*client_data),\n\t\taddr: make(chan *lspnet.UDPAddr),\n\t\tmes: make(chan Message, 1),\n\t\t// current connection id\n\t\tcur_conn_id: 1,\n\t\tclose_client: make(chan int),\n\t\t// send to Write\n\t\tsend: make(chan Message),\n\t\t// send to Read\n\t\tread: make(chan Message, 2500),\n\t\tsend_error: make(chan bool),\n\t\tclosing: false,\n\t\tclosed: make(chan int),\n\t\tone_client_closed: make(chan int, 100),\n\t\tclose_accept: make(chan int, 100),\n\t\tclose_conn_success: make(chan bool),\n\t\tis_client_alive: make(chan int),\n\t\tclient_dead: make(chan int, 100),\n\t\tclose_all: make(chan int,),\n\t}\n\tgo accept(server)\n\tgo serve(server)\n\treturn server, nil\n}", "func NewServer(config *config.Config, metrics *metrics.Metrics) (server Server) {\n\tif config == nil {\n\t\tlog.Fatalf(\"error: config cannot be nil value.\")\n\t}\n\n\tserver.Log = config.Log\n\tserver.ListenPort = config.Server.ListenPort\n\tserver.CacheFolder = config.Server.CacheFolder\n\tserver.MetricsListenPort = config.Server.MetricsListenPort\n\n\tif config.Server.CacheResponse {\n\t\tserver.EnableCache(config.Server.CacheFolder, config.Server.CacheKey)\n\t}\n\n\tserver.Context = config.Context\n\tserver.Router = chi.NewRouter()\n\tserver.HTTP = &http.Server{Addr: \":\" + server.ListenPort, Handler: server.Router}\n\n\t// server.HTTP = &http.Server{\n\t// \tAddr: \":\" + server.ListenPort,\n\t// \tRouter: server.Router,\n\t// \t// Ian Kent recommends these timeouts be set:\n\t// \t// https://www.youtube.com/watch?v=YF1qSfkDGAQ&t=333s\n\t// \tIdleTimeout: time.Duration(time.Second), // This one second timeout may be too aggressive..*shrugs* :)\n\t// \tReadTimeout: time.Duration(time.Second),\n\t// \tWriteTimeout: time.Duration(time.Second),\n\t// }\n\n\tserver.DB = db.NewSimpleDB()\n\tserver.Metrics = metrics\n\treturn\n}", "func NewServer(dir string) *Server {\n\tserver := &Server{\n\t\tRouter: devutil.NewMux(),\n\t\tstatements: t.NewStatementList(),\n\t}\n\tserver.initRoutes()\n\tif dir != \"\" {\n\t\tserver.initWasm(dir)\n\t}\n\tserver.statements.AddExampleData()\n\n\treturn server\n}", "func newServer() *geoServer {\n\ts := new(geoServer)\n\ts.loadLocations(data.MustAsset(\"data/locations.json\"))\n\treturn s\n}", "func NewServer(ln net.Listener, id metainfo.Hash, h Handler, c ...Config) *Server {\n\tif id.IsZero() {\n\t\tpanic(\"the peer node id must not be empty\")\n\t}\n\n\tvar conf Config\n\tconf.set(c...)\n\treturn &Server{Listener: ln, ID: id, Handler: h, Config: conf}\n}", "func New(cfg *config.Config) (*Server, error) {\n\tstorageMgr, err := storage.NewManager(cfg)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to create storage manager\")\n\t}\n\n\tsourceClient, err := source.NewSourceClient()\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to create source client\")\n\t}\n\t// progress manager\n\tprogressMgr, err := progress.NewManager(cfg)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to create progress manager\")\n\t}\n\n\t// cdn manager\n\tcdnMgr, err := cdn.NewManager(cfg, storageMgr, progressMgr, sourceClient)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to create cdn manager\")\n\t}\n\n\t// task manager\n\ttaskMgr, err := task.NewManager(cfg, cdnMgr, progressMgr, sourceClient)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to create task manager\")\n\t}\n\tstorageMgr.SetTaskMgr(taskMgr)\n\tstorageMgr.InitializeCleaners()\n\tprogressMgr.SetTaskMgr(taskMgr)\n\t// gc manager\n\tgcMgr, err := gc.NewManager(cfg, taskMgr, cdnMgr)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to create gc manager\")\n\t}\n\n\treturn &Server{\n\t\tConfig: cfg,\n\t\tTaskMgr: taskMgr,\n\t\tGCMgr: gcMgr,\n\t}, nil\n}", "func New(initCtx context.Context, c *configpb.ServerConf, l *logger.Logger) (*Server, error) {\n\tconn, err := Listen(&net.UDPAddr{Port: int(c.GetPort())}, l)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgo func() {\n\t\t<-initCtx.Done()\n\t\tconn.Close()\n\t}()\n\n\ts := &Server{\n\t\tc: c,\n\t\tconn: conn,\n\t\tl: l,\n\t}\n\n\treturn s, s.initConnection()\n}", "func NewServer(opts ...Option) AtlasServer {\n\tatlas := &server{\n\t\tcurr: newRunningTraces(),\n\t}\n\tfor _, opt := range opts {\n\t\topt(&atlas.opts)\n\t}\n\tatlas.tc = newTokenCache(atlas.opts.ca)\n\tatlas.limit = rate.NewLimiter(rate.Every(time.Millisecond*12), 5000)\n\treturn atlas\n}", "func New(logger log.Logger, ints, chars metrics.Counter) AddServer {\n\tvar svc Service\n\t{\n\t\tsvc = NewBasicService()\n\t\tsvc = LoggingMiddleware(logger)(svc)\n\t\tsvc = InstrumentingMiddleware(ints, chars)(svc)\n\t}\n\treturn svc\n}", "func StartServer(lis net.Listener) (*Server, func(), error) {\n\tif lis == nil {\n\t\tvar err error\n\t\tlis, err = net.Listen(\"tcp\", \"localhost:0\")\n\t\tif err != nil {\n\t\t\treturn nil, func() {}, fmt.Errorf(\"net.Listen() failed: %v\", err)\n\t\t}\n\t}\n\n\ts := NewServer(lis.Addr().String())\n\twp := &wrappedListener{\n\t\tListener: lis,\n\t\tserver: s,\n\t}\n\n\tserver := grpc.NewServer()\n\tv3lrsgrpc.RegisterLoadReportingServiceServer(server, s)\n\tv3discoverygrpc.RegisterAggregatedDiscoveryServiceServer(server, s)\n\tgo server.Serve(wp)\n\n\treturn s, func() { server.Stop() }, nil\n}", "func NewServer(host string, port int) *Server {\n\n\tlpSrv := longpoll.NewLongPoll()\n\tsrv := &Server{\n\t\tlpSrv: lpSrv,\n\t}\n\tmux := gin.New()\n\tmux.GET(\"/sub\", srv.longpollHandler)\n\tmux.POST(\"/pub\", srv.publish)\n\tsrv.httpSrv = &http.Server{\n\t\tAddr: fmt.Sprintf(\"%s:%d\", host, port),\n\t\tHandler: mux,\n\t}\n\treturn srv\n}", "func NewServer(rpc *cosmos.RPC, eventPublisher *publisher.EventPublisher, tokenToRunnerHash *sync.Map, logger tmlog.Logger) *Server {\n\treturn &Server{\n\t\trpc: rpc,\n\t\teventPublisher: eventPublisher,\n\t\ttokenToRunnerHash: tokenToRunnerHash,\n\t\texecInProgress: &sync.Map{},\n\t\tlogger: logger,\n\t}\n}", "func NewServer(configFile string) (*Server, error) {\n\tmanager := schema.GetManager()\n\tconfig := util.GetConfig()\n\terr := config.ReadConfig(configFile)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Config load error: %s\", err)\n\t}\n\terr = os.Chdir(path.Dir(configFile))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Chdir error: %s\", err)\n\t}\n\terr = l.SetUpLogging(config)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Logging setup error: %s\", err)\n\t}\n\tlog.Info(\"logging initialized\")\n\n\tserver := &Server{}\n\n\tm := martini.Classic()\n\tm.Handlers()\n\tm.Use(middleware.WithContext())\n\tm.Use(middleware.Tracing())\n\tm.Use(middleware.Logging())\n\tm.Use(middleware.Metrics())\n\tm.Use(martini.Recovery())\n\tm.Use(middleware.JSONURLs())\n\n\tserver.martini = m\n\n\tport := os.Getenv(\"PORT\")\n\n\tif port == \"\" {\n\t\tport = \"9091\"\n\t}\n\n\tserver.extensions = config.GetStringList(\"extension/use\", []string{\n\t\t\"goext\",\n\t\t\"javascript\",\n\t})\n\tschema.DefaultExtension = config.GetString(\"extension/default\", \"javascript\")\n\n\tmanager.TimeLimit = time.Duration(config.GetInt(\"extension/timelimit\", 30)) * time.Second\n\n\tif config.GetList(\"extension/timelimits\", nil) != nil {\n\t\ttimeLimitList := config.GetList(\"extension/timelimits\", nil)\n\t\tfor _, timeLimit := range timeLimitList {\n\t\t\tcfgRaw := timeLimit.(map[string]interface{})\n\t\t\tcfgPath := cfgRaw[\"path\"].(string)\n\t\t\tcfgEvent := cfgRaw[\"event\"].(string)\n\t\t\tcfgTimeDuration := cfgRaw[\"timelimit\"].(int)\n\n\t\t\tmanager.TimeLimits = append(manager.TimeLimits, &schema.PathEventTimeLimit{\n\t\t\t\tPathRegex: regexp.MustCompile(cfgPath),\n\t\t\t\tEventRegex: regexp.MustCompile(cfgEvent),\n\t\t\t\tTimeDuration: time.Second * time.Duration(cfgTimeDuration),\n\t\t\t})\n\t\t}\n\t}\n\n\tserver.address = config.GetString(\"address\", \":\"+port)\n\tif config.GetBool(\"tls/enabled\", false) {\n\t\tlog.Info(\"TLS enabled\")\n\t\tserver.tls = &tlsConfig{\n\t\t\tKeyFile: config.GetString(\"tls/key_file\", \"./etc/key.pem\"),\n\t\t\tCertFile: config.GetString(\"tls/cert_file\", \"./etc/cert.pem\"),\n\t\t}\n\t}\n\n\tserver.sync, err = sync_util.CreateFromConfig(config)\n\tif err != nil {\n\t\tlog.Error(\"Failed to create sync, err: %s\", err)\n\t\treturn nil, err\n\t}\n\n\tif dbErr := server.connectDB(); dbErr != nil {\n\t\tlog.Fatalf(\"Error while connecting to DB: %s\", dbErr)\n\t}\n\n\tschemaFiles := config.GetStringList(\"schemas\", nil)\n\tif schemaFiles == nil {\n\t\tlog.Fatal(\"No schema specified in configuration\")\n\t} else {\n\t\terr = manager.LoadSchemasFromFiles(schemaFiles...)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"invalid schema: %s\", err)\n\t\t}\n\t}\n\n\tif !config.GetBool(\"database/no_init\", false) {\n\t\tserver.initDB()\n\t}\n\n\tif err = metrics.SetupMetrics(config, server.address); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif config.GetList(\"database/initial_data\", nil) != nil {\n\t\tinitialDataList := config.GetList(\"database/initial_data\", nil)\n\t\tfor _, initialData := range initialDataList {\n\t\t\tinitialDataConfig := initialData.(map[string]interface{})\n\t\t\tfilePath := initialDataConfig[\"connection\"].(string)\n\t\t\tlog.Info(\"Importing data from %s ...\", filePath)\n\t\t\tsource, err := initializer.NewInitializer(filePath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\tdbutil.CopyDBResources(source, server.db, false)\n\t\t}\n\t}\n\n\tm.Map(middleware.NewNobodyResourceService(manager.NobodyResourcePaths()))\n\n\tif config.GetBool(\"keystone/use_keystone\", false) {\n\t\tserver.keystoneIdentity, err = middleware.CreateIdentityServiceFromConfig(config)\n\t\tm.MapTo(server.keystoneIdentity, (*middleware.IdentityService)(nil))\n\t\tm.Use(middleware.Authentication())\n\t} else {\n\t\tm.MapTo(&middleware.NoIdentityService{}, (*middleware.IdentityService)(nil))\n\t\tauth := schema.NewAuthorizationBuilder().\n\t\t\tWithTenant(schema.Tenant{ID: \"admin\", Name: \"admin\"}).\n\t\t\tWithRoleIDs(\"admin\").\n\t\t\tBuildAdmin()\n\t\tm.Map(auth)\n\t}\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid base dir: %s\", err)\n\t}\n\n\tif config.GetBool(\"profiling/enabled\", false) {\n\t\tserver.addPprofRoutes()\n\t}\n\tserver.addOptionsRoute()\n\tcors := config.GetString(\"cors\", \"\")\n\tif cors != \"\" {\n\t\tlog.Info(\"Enabling CORS for %s\", cors)\n\t\tif cors == \"*\" {\n\t\t\tlog.Warning(\"cors for * have security issue\")\n\t\t}\n\t\tserver.martini.Use(func(rw http.ResponseWriter, r *http.Request) {\n\t\t\trw.Header().Add(\"Access-Control-Allow-Origin\", cors)\n\t\t\trw.Header().Add(\"Access-Control-Allow-Headers\", \"X-Auth-Token, Content-Type\")\n\t\t\trw.Header().Add(\"Access-Control-Expose-Headers\", \"X-Total-Count\")\n\t\t\trw.Header().Add(\"Access-Control-Allow-Methods\", \"GET,PUT,POST,DELETE\")\n\t\t})\n\t}\n\n\tdocumentRoot := config.GetString(\"document_root\", \"embed\")\n\tif config.GetBool(\"webui_config/enabled\", false) {\n\t\tm.Use(func(res http.ResponseWriter, req *http.Request, c martini.Context) {\n\t\t\tif req.URL.Path != \"/webui/config.json\" {\n\t\t\t\tc.Next()\n\t\t\t\treturn\n\t\t\t}\n\t\t\taddress := config.GetString(\"webui_config/address\", server.address)\n\t\t\tif address[0] == ':' {\n\t\t\t\taddress = \"__HOST__\" + address\n\t\t\t}\n\t\t\tbaseURL := \"http://\" + address\n\t\t\tauthURL := \"http://\" + address + \"/v2.0\"\n\t\t\tif config.GetBool(\"webui_config/tls\", config.GetBool(\"tls/enabled\", false)) {\n\t\t\t\tbaseURL = \"https://\" + address\n\t\t\t\tauthURL = \"https://\" + address + \"/v2.0\"\n\t\t\t}\n\t\t\tauthURL = config.GetString(\"webui_config/auth_url\", authURL)\n\t\t\twebUIConfig := map[string]interface{}{\n\t\t\t\t\"authUrl\": authURL,\n\t\t\t\t\"gohan\": map[string]interface{}{\n\t\t\t\t\t\"schema\": \"/gohan/v0.1/schemas\",\n\t\t\t\t\t\"url\": baseURL,\n\t\t\t\t},\n\t\t\t\t\"routes\": []interface{}{\n\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\"path\": \"\",\n\t\t\t\t\t\t\"viewClass\": \"topView\",\n\t\t\t\t\t\t\"name\": \"top_view\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t\"errorMessages\": map[string]interface{}{\n\t\t\t\t\t\"tokenExpire\": \"The token is expired. Please re-login.\",\n\t\t\t\t},\n\t\t\t\t\"addingRelationDialog\": []interface{}{\n\t\t\t\t\t\"Pet\",\n\t\t\t\t},\n\t\t\t\t\"pageLimit\": 25,\n\t\t\t\t\"loginRequestTimeout\": 30000,\n\t\t\t\t\"extendTokenTime\": 300000,\n\t\t\t}\n\t\t\troutes.ServeJson(res, webUIConfig)\n\t\t})\n\t}\n\tif documentRoot == \"embed\" {\n\t\tm.Use(staticbin.Static(\"public\", util.Asset, staticbin.Options{\n\t\t\tSkipLogging: true,\n\t\t}))\n\t} else {\n\t\tlog.Info(\"Static file serving from %s\", documentRoot)\n\t\tdocumentRootABS, err := filepath.Abs(documentRoot)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tserver.martini.Use(martini.Static(documentRootABS, martini.StaticOptions{\n\t\t\tSkipLogging: true,\n\t\t}))\n\t}\n\tserver.HealthCheck = healthcheck.NewHealthCheck(server.db, server.sync, server.address, config)\n\tserver.mapRoutes()\n\n\treturn server, nil\n}", "func New(c *controller.Controller) *Server {\n\ts := &Server{\n\t\te: echo.New(),\n\t\tc: c,\n\t}\n\n\t// Middleware\n\ts.e.Use(middleware.Logger())\n\ts.e.Use(middleware.Recover())\n\n\ts.populateRoutes()\n\n\treturn s\n}", "func NewServer(port int, params *Params) (Server, error) {\n\taddr, err := lspnet.ResolveUDPAddr(\"udp\", \":\"+strconv.Itoa(port))\n\tif err != nil {\n\t\tfmt.Println(\"Error on ResolveUDPAddr\")\n\t\treturn nil, err\n\t}\n\tudpConn, err2 := lspnet.ListenUDP(\"udp\", addr)\n\tif err2 != nil {\n\t\tfmt.Println(\"Error in ListenUDP\")\n\t\treturn nil, err2\n\t}\n\n\ts := &server{\n\t\tudpConn: udpConn,\n\t\trequestQueue: make(chan *info),\n\t\tnextClientId: 1,\n\t\tparams: params,\n\t\treadResult: make(chan *Message),\n\t\treadRequest: make(chan int),\n\t\treadBlock: make(chan int),\n\t\treadClientLost: make(chan int),\n\t\tcloseRequest: make(chan int),\n\t\tcloseBlock: make(chan int),\n\t\tcloseClientConnectRequest: make(chan int),\n\t\tcloseAcptReadRoutine: make(chan int),\n\t\tcloseReadRoutine: make(chan int),\n\t\tcloseEpochFile: make(chan int),\n\t\twriteTaskQueue: make(chan *shortMessageType),\n\t\twriteResult: make(chan bool),\n\t\tclientMap: make(map[int]*clientTrackingMap),\n\t\treadyToWriteTask: make(chan *writeBackMessage),\n\t\treadStorage: list.New(),\n\t\twriteStorage: list.New(),\n\t\twriteTask: make(chan int),\n\t\tseq: 1,\n\t\tclientAddrSet: make(map[lspnet.UDPAddr]int),\n\t\tticker: time.NewTicker(time.Duration(params.EpochMillis) * time.Millisecond),\n\t\tepochRenew: make(chan int),\n\t\tclientCloseError: make(chan bool),\n\t\tisCalledClose: false,\n\t\tserverClosed: make(chan int),\n\t\tserverAlreadyClosed: false,\n\t\tlostClient: list.New(),\n\t}\n\t// accepting clients && read\n\tgo acceptAndRead(s)\n\n\t// Main server handling routine\n\tgo mainRoutine(s)\n\n\t// A routine for epoch ticker\n\tgo epochFire(s)\n\n\treturn s, nil\n}", "func newServer(listenAddrs []string, notifier chainntnfs.ChainNotifier,\n\tbio lnwallet.BlockChainIO, fundingSigner lnwallet.MessageSigner,\n\twallet *lnwallet.LightningWallet, chanDB *channeldb.DB) (*server, error) {\n\n\tprivKey, err := wallet.GetIdentitykey()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tprivKey.Curve = btcec.S256()\n\n\tlisteners := make([]net.Listener, len(listenAddrs))\n\tfor i, addr := range listenAddrs {\n\t\tlisteners[i], err = brontide.NewListener(privKey, addr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tserializedPubKey := privKey.PubKey().SerializeCompressed()\n\ts := &server{\n\t\tlnwallet: wallet,\n\t\tbio: bio,\n\t\tchainNotifier: notifier,\n\t\tchanDB: chanDB,\n\n\t\tinvoices: newInvoiceRegistry(chanDB),\n\t\tutxoNursery: newUtxoNursery(chanDB, notifier, wallet),\n\t\thtlcSwitch: newHtlcSwitch(),\n\n\t\tidentityPriv: privKey,\n\t\tnodeSigner: newNodeSigner(privKey),\n\n\t\t// TODO(roasbeef): derive proper onion key based on rotation\n\t\t// schedule\n\t\tsphinx: sphinx.NewRouter(privKey, activeNetParams.Params),\n\t\tlightningID: sha256.Sum256(serializedPubKey),\n\n\t\tpersistentPeers: make(map[string]struct{}),\n\t\tpersistentConnReqs: make(map[string][]*connmgr.ConnReq),\n\n\t\tpeersByID: make(map[int32]*peer),\n\t\tpeersByPub: make(map[string]*peer),\n\t\tinboundPeers: make(map[string]*peer),\n\t\toutboundPeers: make(map[string]*peer),\n\n\t\tnewPeers: make(chan *peer, 10),\n\t\tdonePeers: make(chan *peer, 10),\n\n\t\tbroadcastRequests: make(chan *broadcastReq),\n\t\tsendRequests: make(chan *sendReq),\n\n\t\tglobalFeatures: globalFeatures,\n\t\tlocalFeatures: localFeatures,\n\n\t\tqueries: make(chan interface{}),\n\t\tquit: make(chan struct{}),\n\t}\n\n\t// If the debug HTLC flag is on, then we invoice a \"master debug\"\n\t// invoice which all outgoing payments will be sent and all incoming\n\t// HTLCs with the debug R-Hash immediately settled.\n\tif cfg.DebugHTLC {\n\t\tkiloCoin := btcutil.Amount(btcutil.SatoshiPerBitcoin * 1000)\n\t\ts.invoices.AddDebugInvoice(kiloCoin, *debugPre)\n\t\tsrvrLog.Debugf(\"Debug HTLC invoice inserted, preimage=%x, hash=%x\",\n\t\t\tdebugPre[:], debugHash[:])\n\t}\n\n\t// If external IP addresses have been specified, add those to the list\n\t// of this server's addresses.\n\tselfAddrs := make([]net.Addr, 0, len(cfg.ExternalIPs))\n\tfor _, ip := range cfg.ExternalIPs {\n\t\tvar addr string\n\t\t_, _, err = net.SplitHostPort(ip)\n\t\tif err != nil {\n\t\t\taddr = net.JoinHostPort(ip, strconv.Itoa(defaultPeerPort))\n\t\t} else {\n\t\t\taddr = ip\n\t\t}\n\n\t\tlnAddr, err := net.ResolveTCPAddr(\"tcp\", addr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tselfAddrs = append(selfAddrs, lnAddr)\n\t}\n\n\tchanGraph := chanDB.ChannelGraph()\n\n\t// TODO(roasbeef): make alias configurable\n\talias := lnwire.NewAlias(hex.EncodeToString(serializedPubKey[:10]))\n\tself := &channeldb.LightningNode{\n\t\tLastUpdate: time.Now(),\n\t\tAddresses: selfAddrs,\n\t\tPubKey: privKey.PubKey(),\n\t\tAlias: alias.String(),\n\t\tFeatures: globalFeatures,\n\t}\n\n\t// If our information has changed since our last boot, then we'll\n\t// re-sign our node announcement so a fresh authenticated version of it\n\t// can be propagated throughout the network upon startup.\n\t// TODO(roasbeef): don't always set timestamp above to _now.\n\tself.AuthSig, err = discovery.SignAnnouncement(s.nodeSigner,\n\t\ts.identityPriv.PubKey(),\n\t\t&lnwire.NodeAnnouncement{\n\t\t\tTimestamp: uint32(self.LastUpdate.Unix()),\n\t\t\tAddresses: self.Addresses,\n\t\t\tNodeID: self.PubKey,\n\t\t\tAlias: alias,\n\t\t\tFeatures: self.Features,\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to generate signature for \"+\n\t\t\t\"self node announcement: %v\", err)\n\t}\n\tif err := chanGraph.SetSourceNode(self); err != nil {\n\t\treturn nil, fmt.Errorf(\"can't set self node: %v\", err)\n\t}\n\n\ts.chanRouter, err = routing.New(routing.Config{\n\t\tGraph: chanGraph,\n\t\tChain: bio,\n\t\tNotifier: notifier,\n\t\tSendToSwitch: func(firstHop *btcec.PublicKey,\n\t\t\thtlcAdd *lnwire.UpdateAddHTLC) ([32]byte, error) {\n\n\t\t\tfirstHopPub := firstHop.SerializeCompressed()\n\t\t\tdestInterface := chainhash.Hash(sha256.Sum256(firstHopPub))\n\n\t\t\treturn s.htlcSwitch.SendHTLC(&htlcPacket{\n\t\t\t\tdest: destInterface,\n\t\t\t\tmsg: htlcAdd,\n\t\t\t})\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't create router: %v\", err)\n\t}\n\n\ts.discoverSrv, err = discovery.New(discovery.Config{\n\t\tBroadcast: s.broadcastMessage,\n\t\tNotifier: s.chainNotifier,\n\t\tRouter: s.chanRouter,\n\t\tSendToPeer: s.sendToPeer,\n\t\tTrickleDelay: time.Millisecond * 300,\n\t\tProofMatureDelta: 0,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts.rpcServer = newRPCServer(s)\n\ts.breachArbiter = newBreachArbiter(wallet, chanDB, notifier, s.htlcSwitch)\n\n\tvar chanIDSeed [32]byte\n\tif _, err := rand.Read(chanIDSeed[:]); err != nil {\n\t\treturn nil, err\n\t}\n\n\ts.fundingMgr, err = newFundingManager(fundingConfig{\n\t\tIDKey: s.identityPriv.PubKey(),\n\t\tWallet: wallet,\n\t\tNotifier: s.chainNotifier,\n\t\tSignMessage: func(pubKey *btcec.PublicKey, msg []byte) (*btcec.Signature, error) {\n\t\t\tif pubKey.IsEqual(s.identityPriv.PubKey()) {\n\t\t\t\treturn s.nodeSigner.SignMessage(pubKey, msg)\n\t\t\t}\n\n\t\t\treturn fundingSigner.SignMessage(pubKey, msg)\n\t\t},\n\t\tSendAnnouncement: func(msg lnwire.Message) error {\n\t\t\ts.discoverSrv.ProcessLocalAnnouncement(msg,\n\t\t\t\ts.identityPriv.PubKey())\n\t\t\treturn nil\n\t\t},\n\t\tArbiterChan: s.breachArbiter.newContracts,\n\t\tSendToPeer: s.sendToPeer,\n\t\tFindPeer: s.findPeer,\n\t\tTempChanIDSeed: chanIDSeed,\n\t\tFindChannel: func(chanID lnwire.ChannelID) (*lnwallet.LightningChannel, error) {\n\t\t\tdbChannels, err := chanDB.FetchAllChannels()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tfor _, channel := range dbChannels {\n\t\t\t\tif chanID.IsChanPoint(channel.ChanID) {\n\t\t\t\t\treturn lnwallet.NewLightningChannel(wallet.Signer,\n\t\t\t\t\t\tnotifier, channel)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nil, fmt.Errorf(\"unable to find channel\")\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// TODO(roasbeef): introduce closure and config system to decouple the\n\t// initialization above ^\n\n\t// Create the connection manager which will be responsible for\n\t// maintaining persistent outbound connections and also accepting new\n\t// incoming connections\n\tcmgr, err := connmgr.New(&connmgr.Config{\n\t\tListeners: listeners,\n\t\tOnAccept: s.inboundPeerConnected,\n\t\tRetryDuration: time.Second * 5,\n\t\tTargetOutbound: 100,\n\t\tGetNewAddress: nil,\n\t\tDial: noiseDial(s.identityPriv),\n\t\tOnConnection: s.outboundPeerConnected,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts.connMgr = cmgr\n\n\treturn s, nil\n}", "func New() HelloServer {\n\thttp.DefaultServeMux = new(http.ServeMux)\n\treturn HelloServer{\n\t\t&http.Server{\n\t\t\tAddr: \":7100\",\n\t\t},\n\t}\n}", "func NewServer(config config.Config) (*Server, error) {\n\tghClient := gh.NewClient(config.Owner, config.Repo, config.AccessToken)\n\ttranslator := translators.NewBaiduTranslator(translators.BaiduTranslatorOptions{\n\t\tAppid: config.TranslatorConfig.BaiduConfig.AppID,\n\t\tKey: config.TranslatorConfig.BaiduConfig.Key,\n\t})\n\n\tdocGenerator, err := docgenerator.New(ghClient,\n\t\tconfig.Owner, config.Repo,\n\t\tconfig.DocGenerateConfig.RootDir, config.DocGenerateConfig.SwaggerPath, config.DocGenerateConfig.APIDocPath,\n\t\tconfig.DocGenerateConfig.GenerationHour,\n\t\tconfig.DocGenerateConfig.CliDocGeneratorCmd,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Server{\n\t\tlistenAddress: config.HTTPListen,\n\t\tprocessor: processor.New(ghClient, translator, config.Owner, config.Repo),\n\t\tfetcher: fetcher.New(ghClient, config.FetcherConfig.CommitsGap),\n\t\tciNotifier: ci.New(ghClient, config.Owner, config.Repo),\n\t\treporter: reporter.New(ghClient, config.WeeklyReportConfig.ReportDay, config.WeeklyReportConfig.ReportHour),\n\t\tdocGenerator: docGenerator,\n\t}, nil\n}", "func NewServer(conf *Config, be *backend.Backend) (*Server, error) {\n\tauthInterceptor := interceptors.NewAuthInterceptor(be.Config.AuthWebhookURL)\n\tdefaultInterceptor := interceptors.NewDefaultInterceptor()\n\n\topts := []grpc.ServerOption{\n\t\tgrpc.UnaryInterceptor(grpcmiddleware.ChainUnaryServer(\n\t\t\tauthInterceptor.Unary(),\n\t\t\tdefaultInterceptor.Unary(),\n\t\t\tgrpcprometheus.UnaryServerInterceptor,\n\t\t)),\n\t\tgrpc.StreamInterceptor(grpcmiddleware.ChainStreamServer(\n\t\t\tauthInterceptor.Stream(),\n\t\t\tdefaultInterceptor.Stream(),\n\t\t\tgrpcprometheus.StreamServerInterceptor,\n\t\t)),\n\t}\n\n\tif conf.CertFile != \"\" && conf.KeyFile != \"\" {\n\t\tcreds, err := credentials.NewServerTLSFromFile(conf.CertFile, conf.KeyFile)\n\t\tif err != nil {\n\t\t\tlog.Logger.Error(err)\n\t\t\treturn nil, err\n\t\t}\n\t\topts = append(opts, grpc.Creds(creds))\n\t}\n\n\topts = append(opts, grpc.MaxConcurrentStreams(math.MaxUint32))\n\n\tyorkieServiceCtx, yorkieServiceCancel := context.WithCancel(context.Background())\n\n\tgrpcServer := grpc.NewServer(opts...)\n\thealthpb.RegisterHealthServer(grpcServer, health.NewServer())\n\tapi.RegisterYorkieServer(grpcServer, newYorkieServer(yorkieServiceCtx, be))\n\tapi.RegisterClusterServer(grpcServer, newClusterServer(be))\n\tgrpcprometheus.Register(grpcServer)\n\n\treturn &Server{\n\t\tconf: conf,\n\t\tgrpcServer: grpcServer,\n\t\tyorkieServiceCancel: yorkieServiceCancel,\n\t}, nil\n}", "func NewServer(GM *GameManager) *Server {\n serv := &Server{\n GM: GM,\n Clients: new(sync.Map),\n Channels: new(sync.Map),\n Register: make(chan *Client),\n Unregister: make(chan *Client),\n }\n\n // Register events\n GM.Event(EventDefinition{\"connected\", \"fired when a new client connects\", []string{INTERNAL_CHAN, DIRECT_CHAN}})\n GM.Event(EventDefinition{\"disconnect\", \"fired when a client disconnects\", []string{INTERNAL_CHAN, DIRECT_CHAN}})\n\n // Add the default channels\n serv.NewChannels(map[string]ChannelInterface{\n INTERNAL_CHAN: &InternalChannel{},\n DIRECT_CHAN: &Channel{},\n SERVER_CHAN: &ServerChannel{},\n })\n\n return serv\n}", "func NewServer(c *Config) (*Server, error) {\n\t// validate config\n\tif err := validation.Validate.Struct(c); err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid config: %v\", err)\n\t}\n\n\t// create root context\n\tctx, cancel := context.WithCancel(context.Background())\n\n\t// register handlers\n\tmux := runtime.NewServeMux()\n\topts := []grpc.DialOption{grpc.WithInsecure()}\n\terr := proto.RegisterTodosHandlerFromEndpoint(ctx, mux, c.Endpoint, opts)\n\tif err != nil {\n\t\tdefer cancel()\n\t\treturn nil, fmt.Errorf(\"unable to register gateway handler: %v\", err)\n\t}\n\n\ts := Server{\n\t\tcancel: cancel,\n\t\tlog: c.Log,\n\t\tmux: mux,\n\t\tport: c.Port,\n\t}\n\treturn &s, nil\n}", "func NewServer(ev *event.Dispatcher, irc *irc.Manager, jsvm *vm.VM) (*Server, error) {\n\tsrv := &Server{\n\t\tLogger: logrus.StandardLogger(),\n\t\toutputLogHook: newLogFileWriterHook(),\n\n\t\tevents: ev,\n\t\tirc: irc,\n\t\tvm: jsvm,\n\n\t\twindows: NewWindowManager(ev),\n\t\thistory: NewHistoryManager(),\n\t\ttabber: NewTabCompleter(),\n\n\t\tdone: make(chan struct{}),\n\t}\n\tsrv.initUI()\n\tsrv.Logger.SetOutput(srv.windows.Index(0))\n\tsrv.Logger.SetFormatter(&statusFormatter{})\n\tsrv.Logger.AddHook(srv.outputLogHook)\n\treturn srv, nil\n}", "func NewServer(logger zerolog.Logger, l listing.Service, s storemanagement.Service,\n\tauth authetication.Service, addr string) Server {\n\tif l == nil || s == nil || auth == nil || addr == \"\" {\n\t\tlog.Println(\"Unable to start server because services were not configured\")\n\t\tos.Exit(1)\n\t}\n\n\trouter := chi.NewRouter()\n\tserver := Server{\n\t\tlisting: l,\n\t\tsManager: s,\n\t\trouter: router,\n\t\tauth: auth,\n\t\tServer: &http.Server{\n\t\t\tAddr: addr,\n\t\t\tHandler: router,\n\t\t},\n\t}\n\trouter.Use(httplog.RequestLogger(logger))\n\tserver.Routes()\n\treturn server\n}", "func NewServer() *Server {\n\treturn &Server{\n\t\tstatusMap: make(map[string]healthpb.HealthCheckResponse_ServingStatus),\n\t}\n}", "func NewServer(svc Service, config *Config) *Server {\n\tif !config.Debug {\n\t\tgin.SetMode(gin.ReleaseMode)\n\t}\n\n\tserver := &Server{\n\t\tRoutes: initializeRoutes(\n\t\t\t!config.AuthDisabled,\n\t\t\tconfig.TokenURL,\n\t\t\tconfig.Tracer,\n\t\t),\n\t\tservice: svc,\n\t\tconfig: config,\n\t\tTitle: \"Cluster Registry\",\n\t\tVersion: \"0.0.1\",\n\t\tauthDisabled: config.AuthDisabled,\n\t}\n\n\t// enable pprof http endpoints in debug mode\n\tif config.Debug {\n\t\tpprof.Register(server.Routes.Engine)\n\t}\n\n\t// set logrus logger to TextFormatter with no colors\n\tlog.SetFormatter(&log.TextFormatter{DisableColors: true})\n\n\tserver.server = &http.Server{\n\t\tAddr: config.Address,\n\t\tHandler: server.Routes.Engine,\n\t\tReadTimeout: 10 * time.Second,\n\t\tWriteTimeout: 10 * time.Second,\n\t}\n\n\tserver.serviceHealthyFn = svc.Healthy\n\n\tif !config.WellKnownDisabled {\n\t\tserver.Routes.configureWellKnown(server.isHealthy)\n\t}\n\n\t// configure healthz endpoint\n\tserver.Routes.GET(\"/healthz\", healthHandler(server.isHealthy))\n\n\treturn server\n}", "func NewServer(c *support.ConfigT) *ServerT {\n\trenderer := multitemplate.NewRenderer()\n\t// Initialize the error templates.\n\trenderer.AddFromString(\"error/404\", html.ErrorTpl404())\n\trenderer.AddFromString(\"error/500\", html.ErrorTpl500())\n\trenderer.AddFromString(\"default/welcome\", html.WelcomeTpl())\n\n\tr := newRouter(c)\n\tr.HTMLRender = renderer\n\n\ts := &http.Server{\n\t\tAddr: c.HTTPHost + \":\" + c.HTTPPort,\n\t\tHandler: r,\n\t\tMaxHeaderBytes: c.HTTPMaxHeaderBytes,\n\t\tReadTimeout: c.HTTPReadTimeout,\n\t\tReadHeaderTimeout: c.HTTPReadHeaderTimeout,\n\t\tWriteTimeout: c.HTTPWriteTimeout,\n\t\tIdleTimeout: c.HTTPIdleTimeout,\n\t}\n\ts.ErrorLog = zap.NewStdLog(support.Logger.Desugar())\n\n\tif c.HTTPSSLEnabled == true {\n\t\ts.Addr = c.HTTPHost + \":\" + c.HTTPSSLPort\n\t}\n\n\treturn &ServerT{\n\t\tConfig: c,\n\t\tGRPC: nil, // to be implemented\n\t\tHTTP: s,\n\t\tHTMLRenderer: renderer,\n\t\tRouter: r,\n\t}\n}", "func NewServer(\n\taddr string,\n\tcontrollerNS string,\n\tidentityTrustDomain string,\n\tenableH2Upgrade bool,\n\tenableEndpointSlices bool,\n\tk8sAPI *k8s.API,\n\tmetadataAPI *k8s.MetadataAPI,\n\tclusterStore *watcher.ClusterStore,\n\tclusterDomain string,\n\tdefaultOpaquePorts map[uint32]struct{},\n\tshutdown <-chan struct{},\n) (*grpc.Server, error) {\n\tlog := logging.WithFields(logging.Fields{\n\t\t\"addr\": addr,\n\t\t\"component\": \"server\",\n\t})\n\n\t// Initialize indexers that are used across watchers\n\terr := watcher.InitializeIndexers(k8sAPI)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tendpoints, err := watcher.NewEndpointsWatcher(k8sAPI, metadataAPI, log, enableEndpointSlices, \"local\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\topaquePorts, err := watcher.NewOpaquePortsWatcher(k8sAPI, log, defaultOpaquePorts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tprofiles, err := watcher.NewProfileWatcher(k8sAPI, log)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tservers, err := watcher.NewServerWatcher(k8sAPI, log)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsrv := server{\n\t\tpb.UnimplementedDestinationServer{},\n\t\tendpoints,\n\t\topaquePorts,\n\t\tprofiles,\n\t\tservers,\n\t\tclusterStore,\n\t\tenableH2Upgrade,\n\t\tcontrollerNS,\n\t\tidentityTrustDomain,\n\t\tclusterDomain,\n\t\tdefaultOpaquePorts,\n\t\tk8sAPI,\n\t\tmetadataAPI,\n\t\tlog,\n\t\tshutdown,\n\t}\n\n\ts := prometheus.NewGrpcServer()\n\t// linkerd2-proxy-api/destination.Destination (proxy-facing)\n\tpb.RegisterDestinationServer(s, &srv)\n\treturn s, nil\n}", "func NewServer(options ...ServerOption) *Server {\n s := &Server{\n codecs: make(map[string]Codec),\n services: new(serviceMap),\n }\n for _, option := range options {\n option(s)\n }\n return s\n}", "func (metricsServer PrometheusMetricServer) NewServer(address string, pattern string) {\n\thttp.HandleFunc(\"/healthz\", func(w http.ResponseWriter, _ *http.Request) {\n\t\tw.WriteHeader(http.StatusOK)\n\t\tw.Write([]byte(\"OK\"))\n\t})\n\tlog.Printf(\"Starting metrics server at %v\", address)\n\thttp.Handle(pattern, promhttp.HandlerFor(registry, promhttp.HandlerOpts{}))\n\n\t// initialize the total error metric\n\tscalerErrorsTotal.GetMetricWith(prometheus.Labels{})\n\n\tlog.Fatal(http.ListenAndServe(address, nil))\n}", "func NewServer(\n\tctx context.Context,\n\taddr string,\n\tk8sAPI *k8s.API,\n\tgrpcTapServer pb.TapServer,\n\tdisableCommonNames bool,\n) (*Server, error) {\n\tupdateEvent := make(chan struct{})\n\terrEvent := make(chan error)\n\twatcher := pkgTls.NewFsCredsWatcher(pkgk8s.MountPathTLSBase, updateEvent, errEvent).\n\t\tWithFilePaths(pkgk8s.MountPathTLSCrtPEM, pkgk8s.MountPathTLSKeyPEM)\n\tgo func() {\n\t\tif err := watcher.StartWatching(ctx); err != nil {\n\t\t\tlog.Fatalf(\"Failed to start creds watcher: %s\", err)\n\t\t}\n\t}()\n\n\tclientCAPem, allowedNames, usernameHeader, groupHeader, err := serverAuth(ctx, k8sAPI)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// for development\n\tif disableCommonNames {\n\t\tallowedNames = []string{}\n\t}\n\n\tlog := log.WithFields(log.Fields{\n\t\t\"component\": \"tap\",\n\t\t\"addr\": addr,\n\t})\n\n\tclientCertPool := x509.NewCertPool()\n\tclientCertPool.AppendCertsFromPEM([]byte(clientCAPem))\n\n\thttpServer := &http.Server{\n\t\tAddr: addr,\n\t\tReadHeaderTimeout: 15 * time.Second,\n\t\tTLSConfig: &tls.Config{\n\t\t\tClientAuth: tls.VerifyClientCertIfGiven,\n\t\t\tClientCAs: clientCertPool,\n\t\t\tMinVersion: tls.VersionTLS12,\n\t\t},\n\t}\n\n\tvar emptyCert atomic.Value\n\th := &handler{\n\t\tk8sAPI: k8sAPI,\n\t\tusernameHeader: usernameHeader,\n\t\tgroupHeader: groupHeader,\n\t\tgrpcTapServer: grpcTapServer,\n\t\tlog: log,\n\t}\n\n\tlis, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"net.Listen failed with: %w\", err)\n\t}\n\n\ts := &Server{\n\t\tServer: httpServer,\n\t\tlistener: lis,\n\t\trouter: initRouter(h),\n\t\tallowedNames: allowedNames,\n\t\tcertValue: &emptyCert,\n\t\tlog: log,\n\t}\n\ts.Handler = prometheus.WithTelemetry(s)\n\thttpServer.TLSConfig.GetCertificate = s.getCertificate\n\n\tif err := watcher.UpdateCert(s.certValue); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to initialized certificate: %w\", err)\n\t}\n\n\tgo watcher.ProcessEvents(log, s.certValue, updateEvent, errEvent)\n\n\treturn s, nil\n}", "func newServer(config Config) *http.Server {\n\treturn &http.Server{\n\t\tAddr: fmt.Sprintf(\":%s\", config.Port),\n\t\tHandler: newRouter(config),\n\t}\n}", "func NewServer() *Server {\n\ttr := make(chan TimingReport)\n\ts := &Server{\n\t\ttr,\n\t}\n\tgo s.MonitorTimingReports()\n\treturn s\n}", "func NewServer(c Config) (*Server, error) {\n\tswitch {\n\tcase c.ZKTagsPrefix == \"\":\n\t\tfallthrough\n\tcase c.ReadReqRate < 1:\n\t\tfallthrough\n\tcase c.WriteReqRate < 1:\n\t\treturn nil, errors.New(\"invalid configuration parameter(s)\")\n\t}\n\n\trrt, _ := NewRequestThrottle(RequestThrottleConfig{\n\t\tCapacity: 10,\n\t\tRate: c.ReadReqRate,\n\t})\n\n\twrt, _ := NewRequestThrottle(RequestThrottleConfig{\n\t\tCapacity: 10,\n\t\tRate: c.WriteReqRate,\n\t})\n\n\ttcfg := TagHandlerConfig{\n\t\tPrefix: c.ZKTagsPrefix,\n\t}\n\n\tth, _ := NewTagHandler(tcfg)\n\tif c.test {\n\t\tth.Store = newzkTagStorageMock()\n\t}\n\n\treturn &Server{\n\t\tHTTPListen: c.HTTPListen,\n\t\tGRPCListen: c.GRPCListen,\n\t\tTags: th,\n\t\treadReqThrottle: rrt,\n\t\twriteReqThrottle: wrt,\n\t\ttest: c.test,\n\t}, nil\n}", "func NewServer(routinesPool *safe.Pool, entryPoints TCPEntryPoints, entryPointsUDP UDPEntryPoints, watcher *ConfigurationWatcher,\n\tchainBuilder *middleware.ChainBuilder, accessLoggerMiddleware *accesslog.Handler,\n) *Server {\n\tsrv := &Server{\n\t\twatcher: watcher,\n\t\ttcpEntryPoints: entryPoints,\n\t\tchainBuilder: chainBuilder,\n\t\taccessLoggerMiddleware: accessLoggerMiddleware,\n\t\tsignals: make(chan os.Signal, 1),\n\t\tstopChan: make(chan bool, 1),\n\t\troutinesPool: routinesPool,\n\t\tudpEntryPoints: entryPointsUDP,\n\t}\n\n\tsrv.configureSignals()\n\n\treturn srv\n}", "func NewServer() *Server {\n\tserver := &Server{\n\t\tmessages: make(chan []byte, 1),\n\t\tclients: make(map[chan []byte]bool),\n\t\tregister: make(chan chan []byte),\n\t\tunregister: make(chan chan []byte),\n\t}\n\tgo server.listen()\n\treturn server\n}", "func newServer(cert *shared.CertInfo, handler http.Handler) *httptest.Server {\n\tserver := httptest.NewUnstartedServer(handler)\n\tserver.TLS = util.ServerTLSConfig(cert)\n\tserver.StartTLS()\n\treturn server\n}", "func New(\n\taddr string,\n\thandler Handler,\n\tlog *log.Logger,\n\tworkersCount uint8,\n) (srv *Server) {\n\tsrv = &Server{\n\t\taddr: addr,\n\t\thandler: handler,\n\t\tlog: log,\n\t\tClients: newClients(),\n\t\tchStop: make(chan bool, 1),\n\t\tchRequest: make(chan *tRequest, workersCount),\n\t}\n\n\treturn\n}", "func NewServer(options ...ServerOption) *Server {\n\ts := &Server{}\n\n\tfor _, opt := range options {\n\t\topt(s)\n\t}\n\n\tif s.provider == nil {\n\t\ts.provider = NewJoe()\n\t}\n\n\tif s.logger == nil {\n\t\ts.logger = log.New(os.Stderr, \"go-sse: \", log.LstdFlags)\n\t}\n\n\treturn s\n}", "func New(c Config) *http.Server {\n\n\thandler := &RateLimitHandler{\n\t\trecords: map[string]*Record{},\n\t\tlimit: c.Limit,\n\t\twindow: c.Window,\n\t}\n\n\ts := &http.Server{\n\t\tAddr: fmt.Sprintf(\"0.0.0.0:%d\", c.Port),\n\t\tHandler: handler,\n\t}\n\treturn s\n}", "func NewServer(port int, params *Params) (Server, error) {\n\ts := &server{\n\t\tnextConnectId: 1,\n\t\tclients: make(map[int]*abstractClient),\n\t\treadFromClientChan: make(chan *msgPackage),\n\t\twriteToClientChan: make(chan *Message),\n\t\treadRequest: &requestRead{\n\t\t\task: make(chan int),\n\t\t\tresponse: make(chan *Message),\n\t\t},\n\t\twriteRequest: &requestWrite{\n\t\t\task: make(chan []byte),\n\t\t\tconnId: make(chan int),\n\t\t\tresponse: make(chan error),\n\t\t},\n\t\treadList: list.New(),\n\t\twriteList: list.New(),\n\n\t\tflag: false,\n\n\t\t// variables for window size\n\t\twindowSize: params.WindowSize,\n\t\tmapNeedSend: list.New(),\n\n\t\t// variables for epoch\n\t\tepochChan: make(chan int),\n\t\tepochMillis: params.EpochMillis,\n\t\tepochLimit: params.EpochLimit,\n\n\t\t// close\n\t\tdeleteClient: make(chan int),\n\t\tcloseConnRequest: &requestCloseConn{\n\t\t\task: make(chan int),\n\t\t\tgetError: make(chan error),\n\t\t},\n\t\twaitToWriteFinish: false,\n\t\twriteFinished: make(chan int),\n\t\twaitToAckFinish: false,\n\t\tackFinished: make(chan int),\n\t\tcloseRead: make(chan int, 1),\n\t\tcloseEpoch: make(chan int, 1),\n\t\tcloseEvent: make(chan int, 1),\n\n\t\t// close conn\n\t\tcloseConn: make(chan int, 1),\n\t}\n\n\t// start server\n\taddr, err := lspnet.ResolveUDPAddr(\"udp\", \"localhost:\"+strconv.Itoa(port))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconn, err := lspnet.ListenUDP(\"udp\", addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts.conn = conn\n\tgo s.readMessage()\n\tgo s.handleMessage()\n\tgo s.epochFire()\n\n\tfmt.Println(\"new server\")\n\treturn s, nil\n}", "func newEventSourcedServer() *EventSourcedServer {\n\treturn &EventSourcedServer{\n\t\tentities: make(map[string]*EventSourcedEntity),\n\t\tcontexts: make(map[string]*EntityInstanceContext),\n\t}\n}", "func StartServer(addr *string) {\n\thttp.Handle(\"/metrics\", prometheus.Handler())\n\thttp.HandleFunc(\"/\", func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Write([]byte(`<html>\n <head><title>LXC Exporter</title></head>\n <body>\n <h1>LXC Exporter</h1>\n <p><a href=\"/metrics\">Metrics</a></p>\n </body>\n </html>`))\n\t})\n\n\tif err := http.ListenAndServe(*addr, nil); err != nil {\n\t\tlog.Fatalf(\"Error starting HTTP server: %s\", err)\n\t}\n}", "func NewServer(newStorageClient NewStorageClientFunc, blockSizeLimit uint64) *Server {\n\treturn &Server{newStorageClient, blockSizeLimit, make(map[string]bool)}\n}", "func main() {\n\t\n\tlog.Println(\"start of twitter-streamer server -- twitter-streamer .....\")\n\n\tlistener, err := net.Listen(\"tcp\",\"localhost\"+port) // setup listener\n\tif err != nil {\n\t\tlog.Fatalf(\"Server, failed on listen: %v\",err)\n\t}\n\tgrpcServer := grpc.NewServer()\n\tpb.RegisterTweetServiceServer(grpcServer, new(server)) // register the service\n\n\tlog.Printf(\"server listening on port -> %s\\n\",port)\n\t\n\tif err := grpcServer.Serve(listener); err != nil { // listen serve client connections\n\t\tlog.Fatalf(\"Server, failed to server: %v\",err)\n\t}\n}", "func NewServer(gsrv *grpc.Server, readHandler ReadHandler, writeHandler WriteHandler) (*Server, error) {\n\tif readHandler == nil && writeHandler == nil {\n\t\treturn nil, fmt.Errorf(\"readHandler and writeHandler cannot both be nil\")\n\t}\n\n\tserver := &Server{\n\t\tstatus: make(map[string]*pb.QueryWriteStatusResponse),\n\t\treadHandler: readHandler,\n\t\twriteHandler: writeHandler,\n\t\trpc: &grpcService{},\n\t}\n\tserver.rpc.parent = server\n\n\t// Register a server.\n\tpb.RegisterByteStreamServer(gsrv, server.rpc)\n\n\treturn server, nil\n}", "func NewServer(conn *grpc.ClientConn) *Server {\n\treturn &Server{\n\t\ttopoConn: conn,\n\t\tclients: make(map[uint32]*webClient),\n\t}\n}", "func New(cfg *Config) *Server {\n\tdefaultConfig(cfg)\n\tlog.Printf(\"%+v\\n\", cfg)\n\treturn &Server{\n\t\tcfg: cfg,\n\t\thandlers: make([]connectionHandler, cfg.Count),\n\t\tevents: make(chan eventWithData, cfg.Count),\n\t}\n}", "func (l *PageLoop) NewServer(config *ServerConfig) (*http.Server, error) {\n var handler http.Handler\n\n // Configuration for the server\n l.Config = config\n\n // Initialize server multiplexer\n l.Mux = http.NewServeMux()\n\n // Set up a host for our containers\n\tl.Host = NewHost()\n\n // Manager for application mountpoints.\n //\n // Application mountpoints are dynamic (they can be added and removed at runtime)\n // so they need special care.\n l.MountpointManager = NewMountpointManager(l.Config, l.Host)\n\n l.initServices()\n\n\t// Configure application containers.\n\tsys := NewContainer(\"system\", \"System applications.\", true)\n\ttpl := NewContainer(\"template\", \"Application & document templates.\", true)\n\tusr := NewContainer(\"user\", \"User applications.\", false)\n\tl.Host.Add(usr)\n\tl.Host.Add(sys)\n\tl.Host.Add(tpl)\n\n\t// REST API global endpoint (/api/)\n\thandler = RestService(l.Mux, l.Services, l.Host, l.MountpointManager)\n\tl.MountpointManager.MountpointMap[API_URL] = handler\n\tlog.Printf(\"Serving rest service from %s\", API_URL)\n\n\t// Websocket global endpoint (/ws/)\n\thandler = WebsocketService(l.Mux, l.Services, l.Host, l.MountpointManager)\n\tl.MountpointManager.MountpointMap[WEBSOCKET_URL] = handler\n\tlog.Printf(\"Serving websocket service from %s\", WEBSOCKET_URL)\n\n\t// RPC global endpoint (/rpc/)\n /*\n\thandler = RpcService(l.Mux, l.Host)\n\tl.MountpointManager.MountpointMap[RPC_URL] = handler\n\tlog.Printf(\"Serving rpc service from %s\", RPC_URL)\n */\n\n // Collect mountpoints by container name\n if collection, err := l.MountpointManager.Collect(config.Mountpoints, config.UserConfig().Mountpoints); err != nil {\n return nil, err\n // Load the mountpoints using the container map\n } else {\n // Discarding the returned list of applications\n if _, err := l.MountpointManager.LoadCollection(collection); err != nil {\n return nil, err\n }\n }\n\n // Mount containers and the applications within them\n\tl.MountContainer(sys)\n\tl.MountContainer(tpl)\n\tl.MountContainer(usr)\n\n s := &http.Server{\n Addr: config.Addr,\n Handler: ServerHandler{MountpointManager: l.MountpointManager, Mux: l.Mux},\n ReadTimeout: 10 * time.Second,\n WriteTimeout: 10 * time.Second,\n MaxHeaderBytes: 1 << 20,\n }\n\n return s, nil\n}", "func (s *Server) Start() {\n\ts.logger.WithField(\"version\", build.VERSION).Info(\"Starting server\")\n\n\t// Set up the processors for spans:\n\n\t// Use the pre-allocated Workers slice to know how many to start.\n\ts.SpanWorker = NewSpanWorker(\n\t\ts.spanSinks, s.TraceClient, s.Statsd, s.SpanChan, s.logger)\n\n\tgo func() {\n\t\ts.logger.Info(\"Starting Event worker\")\n\t\tdefer func() {\n\t\t\tConsumePanic(s.TraceClient, s.Hostname, recover())\n\t\t}()\n\t\ts.EventWorker.Work()\n\t}()\n\n\ts.logger.WithField(\"n\", s.SpanWorkerGoroutines).Info(\"Starting span workers\")\n\tfor i := 0; i < s.SpanWorkerGoroutines; i++ {\n\t\tgo func() {\n\t\t\tdefer func() {\n\t\t\t\tConsumePanic(s.TraceClient, s.Hostname, recover())\n\t\t\t}()\n\t\t\ts.SpanWorker.Work()\n\t\t}()\n\t}\n\n\tstatsdPool := &sync.Pool{\n\t\t// We +1 this so we an \"detect\" when someone sends us too long of a metric!\n\t\tNew: func() interface{} {\n\t\t\treturn make([]byte, s.metricMaxLength+1)\n\t\t},\n\t}\n\n\ttracePool := &sync.Pool{\n\t\tNew: func() interface{} {\n\t\t\treturn make([]byte, s.traceMaxLengthBytes)\n\t\t},\n\t}\n\n\tfor _, sink := range s.spanSinks {\n\t\tlogrus.WithField(\"sink\", sink.Name()).Info(\"Starting span sink\")\n\t\tif err := sink.Start(s.TraceClient); err != nil {\n\t\t\tlogrus.WithError(err).WithField(\"sink\", sink).Panic(\"Error starting span sink\")\n\t\t}\n\t}\n\n\tfor _, sink := range s.metricSinks {\n\t\tlogrus.WithField(\"sink\", sink.sink.Name()).Info(\"Starting metric sink\")\n\t\tif err := sink.sink.Start(s.TraceClient); err != nil {\n\t\t\tlogrus.WithError(err).WithField(\"sink\", sink).Fatal(\"Error starting metric sink\")\n\t\t}\n\t}\n\n\t// Read Metrics Forever!\n\tconcreteAddrs := make([]net.Addr, 0, len(s.StatsdListenAddrs))\n\tstatsdSource := UdpMetricsSource{\n\t\tlogger: s.logger,\n\t}\n\tfor _, addr := range s.StatsdListenAddrs {\n\t\tconcreteAddrs = append(\n\t\t\tconcreteAddrs, statsdSource.StartStatsd(s, addr, statsdPool))\n\t}\n\ts.StatsdListenAddrs = concreteAddrs\n\n\t// Read Traces Forever!\n\tssfSource := SsfMetricsSource{\n\t\tlogger: s.logger,\n\t}\n\tif len(s.SSFListenAddrs) > 0 {\n\t\tconcreteAddrs := make([]net.Addr, 0, len(s.StatsdListenAddrs))\n\t\tfor _, addr := range s.SSFListenAddrs {\n\t\t\tconcreteAddrs = append(\n\t\t\t\tconcreteAddrs, ssfSource.StartSSF(s, addr, tracePool))\n\t\t}\n\t\ts.SSFListenAddrs = concreteAddrs\n\t} else {\n\t\tlogrus.Info(\"Tracing sockets are not configured - not reading trace socket\")\n\t}\n\n\t// Read grpc traces forever!\n\tif len(s.GRPCListenAddrs) > 0 {\n\t\tconcreteAddrs := make([]net.Addr, 0, len(s.GRPCListenAddrs))\n\t\tgrpcSource := GrpcMetricsSource{\n\t\t\tlogger: s.logger,\n\t\t}\n\t\tfor _, addr := range s.GRPCListenAddrs {\n\t\t\tconcreteAddrs = append(concreteAddrs, grpcSource.StartGRPC(s, addr))\n\t\t}\n\t\t//If there are already ssf listen addresses then append the grpc ones otherwise just use the grpc ones\n\t\tif len(s.SSFListenAddrs) > 0 {\n\t\t\ts.SSFListenAddrs = append(s.SSFListenAddrs, concreteAddrs...)\n\t\t} else {\n\t\t\ts.SSFListenAddrs = concreteAddrs\n\t\t}\n\n\t\t//If there are already statsd listen addresses then append the grpc ones otherwise just use the grpc ones\n\t\tif len(s.StatsdListenAddrs) > 0 {\n\t\t\ts.StatsdListenAddrs = append(s.StatsdListenAddrs, concreteAddrs...)\n\t\t} else {\n\t\t\ts.StatsdListenAddrs = concreteAddrs\n\t\t}\n\t} else {\n\t\tlogrus.Info(\"GRPC tracing sockets are not configured - not reading trace socket\")\n\t}\n\n\t// Initialize a gRPC connection for forwarding\n\tvar err error\n\tif s.Config.Tls != nil && s.Config.Tls.CaFile != \"\" && s.Config.Tls.CertFile != \"\" && s.Config.Tls.KeyFile != \"\" {\n\t\tvar tlsConfig *tls.Config\n\t\ttlsConfig, err = s.Config.Tls.GetTlsConfig()\n\t\tif err != nil {\n\t\t\ts.logger.WithError(err).Fatal(\"failed to parse tls config\")\n\t\t}\n\t\ts.grpcForwardConn, err = grpc.Dial(\n\t\t\ts.ForwardAddr,\n\t\t\tgrpc.WithTransportCredentials(credentials.NewTLS(tlsConfig)))\n\t} else {\n\t\ts.grpcForwardConn, err = grpc.Dial(s.ForwardAddr, grpc.WithInsecure())\n\t}\n\tif err != nil {\n\t\ts.logger.WithError(err).WithFields(logrus.Fields{\n\t\t\t\"forwardAddr\": s.ForwardAddr,\n\t\t}).Fatal(\"Failed to initialize a gRPC connection for forwarding\")\n\t}\n\n\t// Flush every Interval forever!\n\tgo func() {\n\t\tdefer func() {\n\t\t\tConsumePanic(s.TraceClient, s.Hostname, recover())\n\t\t}()\n\n\t\tctx, cancel := context.WithCancel(context.Background())\n\t\tgo func() {\n\t\t\t// If the server is shutting down, cancel any in-flight flush:\n\t\t\t<-s.shutdown\n\t\t\tcancel()\n\t\t}()\n\n\t\tif s.synchronizeInterval {\n\t\t\t// We want to align our ticker to a multiple of its duration for\n\t\t\t// convenience of bucketing.\n\t\t\t<-time.After(CalculateTickDelay(s.Interval, time.Now()))\n\t\t}\n\n\t\t// We aligned the ticker to our interval above. It's worth noting that just\n\t\t// because we aligned once we're not guaranteed to be perfect on each\n\t\t// subsequent tick. This code is small, however, and should service the\n\t\t// incoming tick signal fast enough that the amount we are \"off\" is\n\t\t// negligible.\n\t\tticker := time.NewTicker(s.Interval)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-s.shutdown:\n\t\t\t\t// stop flushing on graceful shutdown\n\t\t\t\tticker.Stop()\n\t\t\t\treturn\n\t\t\tcase triggered := <-ticker.C:\n\t\t\t\tctx, cancel := context.WithDeadline(ctx, triggered.Add(s.Interval))\n\t\t\t\ts.Flush(ctx)\n\t\t\t\tcancel()\n\t\t\t}\n\t\t}\n\t}()\n}", "func NewServer(addr string, d *Dispatcher, coll *docstore.Collection) *http.Server {\n\tmux := http.NewServeMux()\n\n\tmux.HandleFunc(\"/\", func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Write([]byte(\"hello, vlv.\"))\n\t})\n\n\tmux.HandleFunc(\"/add\", func(w http.ResponseWriter, r *http.Request) {\n\t\tctx := r.Context()\n\n\t\tif r.Method != http.MethodPost {\n\t\t\tw.WriteHeader(http.StatusMethodNotAllowed)\n\t\t\treturn\n\t\t}\n\n\t\tt, err := TaskFromRequest(r)\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tfmt.Fprintf(w, \"failed to decode: %s\", err)\n\t\t\treturn\n\t\t}\n\n\t\tif err := coll.Create(ctx, t); err != nil {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tfmt.Fprintf(w, \"failed to create: %s\", err)\n\t\t\treturn\n\t\t}\n\n\t\tb, err := json.MarshalIndent(&t, \"\", \" \")\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tfmt.Fprintf(w, \"failed to marshal: %s\", err)\n\t\t\treturn\n\t\t}\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Write(b)\n\t})\n\n\tmux.HandleFunc(\"/tasks\", func(w http.ResponseWriter, r *http.Request) {\n\t\tctx := r.Context()\n\n\t\titer := coll.Query().Get(ctx)\n\t\tdefer iter.Stop()\n\n\t\ttasks := make([]*Task, 0)\n\t\tfor {\n\t\t\tvar t Task\n\t\t\tif err := iter.Next(ctx, &t); err == io.EOF {\n\t\t\t\tbreak\n\t\t\t} else if err != nil {\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\tfmt.Fprintf(w, \"failed to store the next: %s\", err)\n\t\t\t\treturn\n\t\t\t} else {\n\t\t\t\ttasks = append(tasks, &t)\n\t\t\t}\n\t\t}\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\terr := json.NewEncoder(w).Encode(&struct {\n\t\t\tTasks []*Task `json:\"tasks\"`\n\t\t}{\n\t\t\tTasks: tasks,\n\t\t})\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tw.Header().Set(\"Content-Type\", \"plain/text\")\n\t\t\tfmt.Fprintf(w, \"failed to encode tasks: %s\", err)\n\t\t}\n\t})\n\n\tmux.HandleFunc(\"/status\", func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tif err := json.NewEncoder(w).Encode(d.Status()); err != nil {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tw.Header().Set(\"Content-Type\", \"plain/text\")\n\t\t\tfmt.Fprintf(w, \"failed to encode status: %s\", err)\n\t\t}\n\t})\n\n\tmux.HandleFunc(\"/open\", func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method != http.MethodPost {\n\t\t\tw.WriteHeader(http.StatusMethodNotAllowed)\n\t\t\treturn\n\t\t}\n\n\t\td.shut = false\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tif err := json.NewEncoder(w).Encode(d.Status()); err != nil {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tw.Header().Set(\"Content-Type\", \"plain/text\")\n\t\t\tfmt.Fprintf(w, \"failed to encode status: %s\", err)\n\t\t}\n\t})\n\n\tmux.HandleFunc(\"/shut\", func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method != http.MethodPost {\n\t\t\tw.WriteHeader(http.StatusMethodNotAllowed)\n\t\t\treturn\n\t\t}\n\n\t\td.shut = true\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tif err := json.NewEncoder(w).Encode(d.Status()); err != nil {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tw.Header().Set(\"Content-Type\", \"plain/text\")\n\t\t\tfmt.Fprintf(w, \"failed to encode status: %s\", err)\n\t\t}\n\t})\n\n\treturn &http.Server{\n\t\tAddr: addr,\n\t\tHandler: mux,\n\t}\n}", "func New() *Server {\n\ts := &Server{\n\t\thandlers: map[string][]HandlerFunc{},\n\t\tclosing: make(chan struct{}),\n\t\tclosed: make(chan struct{}),\n\t}\n\ts.pool.New = func() interface{} {\n\t\treturn s.allocateContext()\n\t}\n\treturn s\n}", "func NewServer(service waqi.Service, listenAddr string, logger *log.Logger) (Server, error) {\n\tgin.SetMode(gin.ReleaseMode)\n\n\trouter := gin.New()\n\trouter.Use(gin.Recovery())\n\thttp.Handle(\"/\", router)\n\n\t// REST API\n\tcontroller := &restController{service: service}\n\trouter.GET(\"/api/status/geo\", controller.GetByGeo)\n\trouter.GET(\"/api/status/city/:city\", controller.GetByCity)\n\trouter.GET(\"/api/status/station/:id\", controller.GetByStation)\n\n\t// Static files\n\terr := mime.AddExtensionType(\".js\", \"application/javascript\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trouter.NoRoute(func(c *gin.Context) {\n\t\tdir, file := path.Split(c.Request.RequestURI)\n\t\text := filepath.Ext(file)\n\t\tif file == \"\" || ext == \"\" {\n\t\t\tc.File(\"./www/index.html\")\n\t\t} else {\n\t\t\tc.File(\"./www\" + path.Join(dir, file))\n\t\t}\n\t})\n\n\ts := &server{\n\t\tlistenAddr: listenAddr,\n\t\tdone: make(chan bool),\n\t\tlogger: logger,\n\t}\n\treturn s, nil\n}", "func NewServer(port int, source TrackSource, sink TrackSink, control PlaybackControl) Server {\n\ts := Server{\n\t\tport: port,\n\t\tsource: source,\n\t\tsink: sink,\n\t\tcontrol: control,\n\t\ttracks: make(chan Track, 0),\n\t}\n\tsource.RegisterTrackOutChan(s.tracks)\n\tsink.RegisterTrackInChan(s.tracks)\n\treturn s\n}", "func NewServer(config *config.Config, appCache *cache.AppCache, mySql *db.MysqlDB) *HttpServer {\n\ts := Server{\n\t\tConfig: config,\n\t\tInventory: &service.Inventory{\n\t\t\tAppCache: appCache,\n\t\t\tMysql: mySql,\n\t\t},\n\t}\n\n\t// Create a HTTP server for prometheus.\n\tserveMux := http.NewServeMux()\n\tserveMux.HandleFunc(\"/getQuantity\", func(res http.ResponseWriter, req *http.Request) {\n\t\ts.getQuantity(res, req)\n\t})\n\tserveMux.HandleFunc(\"/addQuantity\", func(res http.ResponseWriter, req *http.Request) {\n\t\ts.addQuantity(res, req)\n\t})\n\tserveMux.HandleFunc(\"/addNegativeQuantity\", func(res http.ResponseWriter, req *http.Request) {\n\t\ts.addNegativeQuantity(res, req)\n\t})\n\n\treturn &HttpServer{\n\t\tServeMux: serveMux,\n\t\tConfig: config,\n\t}\n}", "func NewServer(ctx context.Context, cfg execinfra.ServerConfig) *ServerImpl {\n\tds := &ServerImpl{\n\t\tServerConfig: cfg,\n\t\tregexpCache: tree.NewRegexpCache(512),\n\t\tflowRegistry: flowinfra.NewFlowRegistry(cfg.NodeID.SQLInstanceID()),\n\t\tflowScheduler: flowinfra.NewFlowScheduler(cfg.AmbientContext, cfg.Stopper, cfg.Settings, cfg.Metrics),\n\t\tmemMonitor: mon.NewMonitor(\n\t\t\t\"distsql\",\n\t\t\tmon.MemoryResource,\n\t\t\tcfg.Metrics.CurBytesCount,\n\t\t\tcfg.Metrics.MaxBytesHist,\n\t\t\t-1, /* increment: use default block size */\n\t\t\tnoteworthyMemoryUsageBytes,\n\t\t\tcfg.Settings,\n\t\t),\n\t}\n\tds.memMonitor.Start(ctx, cfg.ParentMemoryMonitor, mon.BoundAccount{})\n\n\tcolexec.HashAggregationDiskSpillingEnabled.SetOnChange(&cfg.Settings.SV, func() {\n\t\tif !colexec.HashAggregationDiskSpillingEnabled.Get(&cfg.Settings.SV) {\n\t\t\ttelemetry.Inc(sqltelemetry.HashAggregationDiskSpillingDisabled)\n\t\t}\n\t})\n\n\treturn ds\n}", "func New(e *step.Endpoints, uh goagrpc.UnaryHandler) *Server {\n\treturn &Server{\n\t\tListH: NewListHandler(e.List, uh),\n\t\tAddH: NewAddHandler(e.Add, uh),\n\t\tRemoveH: NewRemoveHandler(e.Remove, uh),\n\t\tUpdateH: NewUpdateHandler(e.Update, uh),\n\t}\n}", "func New(addr string) *Server {\n\tsrv := new(Server)\n\tsrv.Context = new(Context)\n\tsrv.Context.Channels = make(map[string]*channel.Channel)\n\tsrv.Address = addr\n\treturn srv\n}" ]
[ "0.6450294", "0.6137566", "0.6124656", "0.60456717", "0.5995859", "0.598988", "0.5989809", "0.598493", "0.5978896", "0.59556425", "0.59531736", "0.5947071", "0.5943734", "0.5936937", "0.5906985", "0.5880917", "0.58790934", "0.5876771", "0.5866584", "0.5829714", "0.5829714", "0.5826772", "0.5818666", "0.5783269", "0.5774967", "0.5773494", "0.5766784", "0.5764091", "0.5755774", "0.5753904", "0.5752077", "0.5738661", "0.57386297", "0.573859", "0.5738088", "0.57234305", "0.5716638", "0.5715846", "0.57091004", "0.5696886", "0.56951785", "0.56837744", "0.5676832", "0.56738114", "0.5671082", "0.56684005", "0.5668001", "0.5667165", "0.5666054", "0.56531376", "0.56480724", "0.5637947", "0.5635429", "0.5624273", "0.560996", "0.5605313", "0.56050706", "0.56022805", "0.5600333", "0.5594661", "0.5585319", "0.55841106", "0.55836236", "0.55819434", "0.5578559", "0.5571297", "0.5565996", "0.556209", "0.5560985", "0.55567384", "0.5552672", "0.55431753", "0.5542422", "0.55357635", "0.55319184", "0.5524567", "0.5522278", "0.5520054", "0.5519474", "0.55157626", "0.551576", "0.5513626", "0.5511277", "0.55065256", "0.5502539", "0.54979587", "0.549396", "0.549376", "0.5491297", "0.54865986", "0.5485627", "0.5470868", "0.5467398", "0.5464148", "0.5463066", "0.5462886", "0.5459466", "0.5456566", "0.54547375", "0.54501975" ]
0.78174824
0
NewUInt64 creates a new UInt64 with default values.
NewUInt64 создает новый UInt64 с default значениями.
func NewUInt64() *UInt64 { self := UInt64{} self.SetDefaults() return &self }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewUint64(x uint64) *Numeric {\n\tvar r Numeric\n\treturn r.SetUint64(x)\n}", "func NewUint64(store *store.Store, cfgPath string) *Uint64 {\n\tf := &Uint64{}\n\tf.init(store, f.mapCfgValue, cfgPath)\n\treturn f\n}", "func NewUint64(value uint64) *Uint64 {\n\treturn &Uint64{\n\t\tvalue: value,\n\t}\n}", "func NewUint64(inp uint64) B64 {\n\tvar resp = []B64{\n\t\tnewUint64(inp),\n\t}\n\treturn resp[0]\n}", "func NewUint64(vals ...uint64) Uint64 {\n\tsize := max(len(vals), minSize)\n\tset := Uint64{\n\t\tm: make(map[uint64]struct{}, size),\n\t}\n\tset.Add(vals...)\n\treturn set\n}", "func NewOptionalUInt64(v interface{}) *OptionalUInt64 {\n\ts, ok := v.(uint64)\n\tif ok {\n\t\treturn &OptionalUInt64{Value: s}\n\t}\n\treturn nil\n}", "func NewUint64(data arrow.ArrayData, shape, strides []int64, names []string) *Uint64 {\n\ttsr := &Uint64{tensorBase: *newTensor(arrow.PrimitiveTypes.Uint64, data, shape, strides, names)}\n\tvals := tsr.data.Buffers()[1]\n\tif vals != nil {\n\t\ttsr.values = arrow.Uint64Traits.CastFromBytes(vals.Bytes())\n\t\tbeg := tsr.data.Offset()\n\t\tend := beg + tsr.data.Len()\n\t\ttsr.values = tsr.values[beg:end]\n\t}\n\treturn tsr\n}", "func (c Uint64Codec) New() unsafe.Pointer {\n\treturn unsafe.Pointer(new(uint64))\n}", "func NewUint64WithSize(size int) Uint64 {\n\tset := Uint64{\n\t\tm: make(map[uint64]struct{}, size),\n\t}\n\treturn set\n}", "func NewTagUint64(ls *lua.LState) int {\n\tvar val = uint64(ls.CheckInt(1))\n\tPushTag(ls, &LuaTag{wpk.TagUint64(val)})\n\treturn 1\n}", "func UInt64(v uint64) *uint64 {\n\treturn &v\n}", "func NewUint64Setting(name string, description string, fallback uint64) *Uint64Setting {\n\treturn &Uint64Setting{\n\t\tBaseSetting: &BaseSetting{\n\t\t\tNameValue: name,\n\t\t\tDescriptionValue: description,\n\t\t},\n\t\tUint64Value: &fallback,\n\t}\n}", "func (c *Client) NewGaugeUint64(name string, opts ...MOption) *GaugeUint64 {\n\tg := &GaugeUint64{name: name}\n\tc.register(g, opts...)\n\treturn g\n}", "func NewRandUint64() (uint64, error) {\n\tvar b [8]byte\n\t_, err := rand.Read(b[:])\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn binary.LittleEndian.Uint64(b[:]), nil\n}", "func Uint64(name string, value uint64, usage string) *uint64 {\n\tp := new(uint64);\n\tUint64Var(p, name, value, usage);\n\treturn p;\n}", "func MakeUInt64(in *uint64) *google_protobuf.UInt64Value {\n\tif in == nil {\n\t\treturn nil\n\t}\n\n\treturn &google_protobuf.UInt64Value{\n\t\tValue: *in,\n\t}\n}", "func MakeUInt64OrDefault(in *uint64, defaultValue uint64) *google_protobuf.UInt64Value {\n\tif in == nil {\n\t\treturn &google_protobuf.UInt64Value{\n\t\t\tValue: defaultValue,\n\t\t}\n\t}\n\n\treturn &google_protobuf.UInt64Value{\n\t\tValue: *in,\n\t}\n}", "func NewUint64VarP(\n\tlabel string,\n\tshortLabel string,\n\tdefaultValue uint64,\n\tdescription string,\n) Flag {\n\treturn &uint64VarP{\n\t\tflagBase: flagBase{\n\t\t\tlabel: label,\n\t\t\tshortLabel: shortLabel,\n\t\t\tdescription: description,\n\t\t},\n\t\tdefaultValue: defaultValue,\n\t}\n}", "func (s *OptionalUInt64) UInt64() uint64 {\n\treturn s.Value\n}", "func New64(seed uint32) Hash128 {\n\tseed64 := uint64(seed)\n\treturn &sum64_128{seed64, seed64, 0, 0, 0, 0}\n}", "func NewUID() uint64 {\n\tvar v uint64\n\terr := binary.Read(rand.Reader, binary.BigEndian, &v)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\treturn v\n}", "func NewUInt64Set() UInt64Set {\n\treturn make(map[uint64]struct{})\n}", "func Uint64(uint64 uint64) *uint64 {\n\treturn &uint64\n}", "func (i *UInt64) UInt64() uint64 {\n\treturn uint64(*i)\n}", "func Uint64(name string, value uint64, usage string) *uint64 {\n\treturn Environment.Uint64(name, value, usage)\n}", "func New64() hash.Hash64 { return New64WithSeed(0) }", "func NewUint64Uint64Map(kv ...Uint64Uint64Tuple) Uint64Uint64Map {\n\tmm := newUint64Uint64Map()\n\tfor _, t := range kv {\n\t\tmm[t.Key] = t.Val\n\t}\n\treturn mm\n}", "func Uint64() uint64 { return globalRand.Uint64() }", "func Uint64() uint64 { return globalRand.Uint64() }", "func Uint64() uint64 { return globalRand.Uint64() }", "func NewAutoUInt64Table(prefixData [2]byte, prefixSeq byte, model proto.Message, cdc codec.Codec) (*AutoUInt64Table, error) {\n\ttable, err := newTable(prefixData, model, cdc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &AutoUInt64Table{\n\t\ttable: table,\n\t\tseq: NewSequence(prefixSeq),\n\t}, nil\n}", "func GetUInt64OrDefault(in *google_protobuf.UInt64Value, defaultValue uint64) *uint64 {\n\tif in == nil {\n\t\treturn &defaultValue\n\t}\n\n\treturn &in.Value\n}", "func Uint64() uint64 {\n\treturn uint64(rand.Int63n(math.MaxInt64))\n}", "func New64() *Digest64 {\n\treturn New64WithSeed(0)\n}", "func Uint64(flag string, value uint64, description string) *uint64 {\n\tvar v uint64\n\tUint64Var(&v, flag, value, description)\n\treturn &v\n}", "func Uint64(u *uint64) uint64 {\n\tif u == nil {\n\t\treturn 0\n\t}\n\treturn *u\n}", "func NewUint64Set(items ...uint64) Uint64Set {\n\tss := Uint64Set{}\n\tss.Insert(items...)\n\treturn ss\n}", "func NewBigUInt(i uint64) *BigUInt {\n\treturn &BigUInt{data: bytesFromUInt64(i)}\n}", "func Uint64(name string, defaultValue uint64) uint64 {\n\tif strVal, ok := os.LookupEnv(name); ok {\n\t\tif i64, err := strconv.ParseUint(strVal, 10, 64); err == nil {\n\t\t\treturn i64\n\t\t}\n\t}\n\n\treturn defaultValue\n}", "func Uint64(v uint64) *uint64 {\n\treturn &v\n}", "func Uint64(v uint64) *uint64 {\n\treturn &v\n}", "func newUint(value *big.Int, width Width) *TypedUint {\n\ttypedUint64 := TypedUint{\n\t\tBytes: value.Bytes(),\n\t\tType: ValueType_UINT,\n\t\tTypeOpts: []int32{int32(width)},\n\t}\n\treturn &typedUint64\n}", "func u64(wr *wrappers.UInt64Value) *uint64 {\n\tif wr == nil {\n\t\treturn nil\n\t}\n\tresult := new(uint64)\n\t*result = wr.GetValue()\n\n\treturn result\n}", "func Uint64(name string, value uint64, usage string) *uint64 {\n\treturn ex.FlagSet.Uint64(name, value, usage)\n}", "func Uint64(key string, val uint64) Tag {\n\treturn Tag{key: key, tType: uint64Type, integerVal: int64(val)}\n}", "func Uint64(name string, alias rune, value uint64, usage string, fn Callback) *uint64 {\n\treturn CommandLine.Uint64(name, alias, value, usage, fn)\n}", "func Uint64(v *uint64) uint64 {\n\tif v != nil {\n\t\treturn *v\n\t}\n\treturn 0\n}", "func Uint64(name string, val uint64) Field {\n\treturn Field(zap.Uint64(name, val))\n}", "func UInt64(r interface{}, err error) (uint64, error) {\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tswitch r := r.(type) {\n\tcase uint64:\n\t\treturn r, err\n\tcase int:\n\t\tif r < 0 {\n\t\t\treturn 0, simplesessions.ErrAssertType\n\t\t}\n\t\treturn uint64(r), nil\n\tcase int64:\n\t\tif r < 0 {\n\t\t\treturn 0, simplesessions.ErrAssertType\n\t\t}\n\t\treturn uint64(r), nil\n\tcase []byte:\n\t\tn, err := strconv.ParseUint(string(r), 10, 64)\n\t\treturn n, err\n\tcase string:\n\t\tn, err := strconv.ParseUint(r, 10, 64)\n\t\treturn n, err\n\tcase nil:\n\t\treturn 0, simplesessions.ErrNil\n\t}\n\n\treturn 0, simplesessions.ErrAssertType\n}", "func GetU64(name string, defvals ...uint64) uint64 {\n\tif global == nil {\n\t\tif len(defvals) == 0 {\n\t\t\treturn 0\n\t\t}\n\n\t\treturn defvals[0]\n\t}\n\n\treturn global.GetU64(name, defvals...)\n}", "func UInt64NoNonePtr(s uint64) *uint64 {\n\tif s == 0 {\n\t\treturn nil\n\t}\n\treturn &s\n}", "func (no *Node) UInt64() (uint64, error) {\n\tvar out uint64\n\tif err := binary.Read(no.buf, binary.LittleEndian, &out); err != nil {\n\t\treturn 0, err\n\t}\n\treturn out, nil\n}", "func MakeUint64(x uint64) Value {\n\treturn constant.MakeUint64(x)\n}", "func NewUint(u uint) Uint { return &u }", "func Uint64(num uint64) *cells.BinaryCell {\n\treturn cells.New(OpUint64, proto.EncodeVarint(num))\n}", "func Uint64Empty(val interface{}) string {\n\tif val == nil {\n\t\treturn \"\"\n\t}\n\n\treturn strconv.FormatUint(val.(uint64), 10)\n}", "func (r *Rand) Uint64() uint64 {\n\tif x, err := r.cryptoRand.Uint64(); err == nil {\n\t\treturn x\n\t}\n\treturn r.mathRand.Uint64()\n}", "func (s *EnvVarSet) Uint64(name string, value uint64, usage string) *uint64 {\n\tp := new(uint64)\n\n\ts.Uint64Var(p, name, value, usage)\n\n\treturn p\n}", "func Uint64(key string, val uint64) Field {\n\treturn Field{Key: key, Type: core.Uint64Type, Integer: int64(val)}\n}", "func (f *FlagSet) Uint64(name string, alias rune, value uint64, usage string, fn Callback) *uint64 {\n\tp := new(uint64)\n\tf.Uint64Var(p, name, alias, value, usage, fn)\n\treturn p\n}", "func Uint64(k string, v uint64) Field {\n\treturn Field{Key: k, Value: valf.Uint64(v)}\n}", "func (p *PCG64) Uint64() uint64 {\n\tp.multiply()\n\tp.add()\n\t// XOR high and low 64 bits together and rotate right by high 6 bits of state.\n\treturn bits.RotateLeft64(p.high^p.low, -int(p.high>>58))\n}", "func (i *Int64) UInt64() uint64 {\n\treturn uint64(*i)\n}", "func Uint64Arg(register Register, name string, options ...ArgOptionApplyer) *uint64 {\n\tp := new(uint64)\n\t_ = Uint64ArgVar(register, p, name, options...)\n\treturn p\n}", "func NewUint(x uint) *Numeric {\n\tvar r Numeric\n\treturn r.SetUint(x)\n}", "func (u Uint64) Uint64() uint64 {\n\treturn uint64(u)\n}", "func RandomUint64() uint64 {\n\treturn rand.Uint64()\n}", "func (c *Config) GetU64(name string, defvals ...uint64) uint64 {\n\tif len(defvals) != 0 {\n\t\treturn uint64(c.GetI64(name, int64(defvals[0])))\n\t}\n\n\treturn uint64(c.GetI64(name))\n}", "func MeasureUInt64(name string, field string, value uint64) Measurement {\n\treturn NewMeasurement(name).AddUInt64(field, value)\n}", "func (elt *Element) Uint64(defaultValue ...uint64) (uint64, error) {\n\tdefValue := func() *uint64 {\n\t\tif len(defaultValue) == 0 {\n\t\t\treturn nil\n\t\t}\n\t\treturn &defaultValue[0]\n\t}\n\tdef := defValue()\n\tif elt.Value == nil {\n\t\tdef := defValue()\n\t\tif def == nil {\n\t\t\tvar v uint64\n\t\t\treturn v, NewWrongPathError(elt.Path)\n\t\t}\n\t\treturn *def, nil\n\t}\n\tv, ok := elt.Value.(uint64)\n\tif !ok {\n\t\tif def == nil{\n\t\t\tvar v uint64\n\t\t\treturn v, NewWrongTypeError(\"uint64\", elt.Value)\n\t\t}\n\t\treturn *def, nil\n\t}\n\treturn v, nil\n}", "func FormatUint64(format string, v ...any) uint64 {\n\treturn GetUint64(Format(format, v...))\n}", "func NewXXHash64(seed uint64) (*XXHash64, error) {\n\tthis := new(XXHash64)\n\tthis.seed = seed\n\treturn this, nil\n}", "func RandUint64() uint64 {\n\tb := RandBytes(8)\n\treturn binary.BigEndian.Uint64(b)\n}", "func (n BlockNonce) Uint64() uint64 {\n\treturn binary.BigEndian.Uint64(n[:])\n}", "func (n BlockNonce) Uint64() uint64 {\n\treturn binary.BigEndian.Uint64(n[:])\n}", "func NewFromUint64Slice(items []uint64) *SliceOfUint64 {\n\tslicy := &SliceOfUint64{items}\n\treturn slicy\n}", "func Uint64(v interface{}) (uint64, error) {\n\tvar err error\n\tv = indirect(v)\n\n\tswitch n := v.(type) {\n\tcase int8:\n\t\tif n < 0 {\n\t\t\terr = OverflowError{ToType: \"uint64\", Value: v}\n\t\t}\n\t\treturn uint64(n), err\n\tcase int16:\n\t\tif n < 0 {\n\t\t\terr = OverflowError{ToType: \"uint64\", Value: v}\n\t\t}\n\t\treturn uint64(n), err\n\tcase int32:\n\t\tif n < 0 {\n\t\t\terr = OverflowError{ToType: \"uint64\", Value: v}\n\t\t}\n\t\treturn uint64(n), err\n\tcase int64:\n\t\tif n < 0 {\n\t\t\terr = OverflowError{ToType: \"uint64\", Value: v}\n\t\t}\n\t\treturn uint64(n), err\n\tcase int:\n\t\tif n < 0 {\n\t\t\terr = OverflowError{ToType: \"uint64\", Value: v}\n\t\t}\n\t\treturn uint64(n), err\n\tcase uint8:\n\t\treturn uint64(n), err\n\tcase uint16:\n\t\treturn uint64(n), err\n\tcase uint32:\n\t\treturn uint64(n), err\n\tcase uint64:\n\t\treturn n, err\n\tcase uint:\n\t\treturn uint64(n), err\n\t}\n\n\treturn 0, InvalidTypeError{ToType: \"uint64\", Value: v}\n}", "func New64(seed uint64) *Flea64 {\n\tf := &Flea64{\n\t\ta: fleaSeed64,\n\t\tb: seed,\n\t\tc: seed,\n\t\td: seed,\n\t}\n\n\t// Functions with for-loops aren't inlined.\n\t// See https://github.com/golang/go/issues/14768\n\ti := 0\nloop:\n\te := f.a - bits.RotateLeft64(f.b, flea64Rot1)\n\tf.a = f.b ^ bits.RotateLeft64(f.c, flea64Rot2)\n\tf.b = f.c + f.d\n\tf.c = f.d + e\n\tf.d = e + f.a\n\n\ti++\n\tif i < flea64Rounds {\n\t\tgoto loop\n\t}\n\treturn f\n}", "func randomUint64(t *testing.T) uint64 {\n\tbigInt, err := rand.Int(rand.Reader, new(big.Int).SetUint64(math.MaxUint64))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn bigInt.Uint64()\n}", "func (bh *bh_rng) Uint64() (v uint64) {\n\tbinary.Read(bh, binary.BigEndian, &v)\n\treturn\n}", "func NewKeyUint(key uint64) *KeyUint { return &KeyUint{key} }", "func Uint64Var(pv *uint64, flag string, value uint64, description string) {\n\tshort, long, err := parseSingleFlag(flag)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t*pv = value\n\tflags = append(flags, &optionUint64{\n\t\tdescription: description,\n\t\tlong: long,\n\t\tshort: short,\n\t\tpv: pv,\n\t\tdef: value,\n\t})\n}", "func New64(key []byte) (hash.Hash64, error) {\n\tif k := len(key); k != KeySize {\n\t\treturn nil, KeySizeError(k)\n\t}\n\th := new(digest64)\n\th.key[0] = binary.LittleEndian.Uint64(key)\n\th.key[1] = binary.LittleEndian.Uint64(key[8:])\n\th.Reset()\n\treturn h, nil\n}", "func (rng *Rng) Uint64() uint64 {\n\trng.State += 0x9E3779B97F4A7C15\n\tz := rng.State\n\tz = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9\n\tz = (z ^ (z >> 27)) * 0x94D049BB133111EB\n\treturn z ^ (z >> 31)\n}", "func NewUInt8() *UInt8 {\n\tself := UInt8{}\n\tself.SetDefaults()\n\treturn &self\n}", "func randUInt64() uint64 {\n\tbits := rand.Uint32() % 64\n\tif bits == 0 {\n\t\treturn 0\n\t}\n\tn := uint64(1 << (bits - 1))\n\tn += uint64(rand.Int63()) & ((1 << (bits - 1)) - 1)\n\treturn n\n}", "func GetUint64(key string) uint64 { return viper.GetUint64(key) }", "func NewUint(value uint) *Uint {\n\treturn &Uint{\n\t\tvalue: value,\n\t}\n}", "func (m Measurement) AddUInt64(name string, value uint64) Measurement {\n\tm.fieldSet[name] = value\n\treturn m\n}", "func Uint64Tag(name interface{}, value uint64) Tag {\n\treturn &tag{\n\t\ttagType: TagUint64,\n\t\tname: name,\n\t\tvalue: value,\n\t}\n}", "func New() UID {\n\treturn UID{\n\t\tNullUUID: uuid.NullUUID{UUID: uuid.New(), Valid: true},\n\t}\n}", "func Uint64Var(p *uint64, name string, value uint64, usage string) {\n\tadd(name, newUint64Value(value, p), usage)\n}", "func NewUID(param ...int) (string, error) {\n\tvar size int\n\tif len(param) == 0 {\n\t\tsize = defaultSize\n\t} else {\n\t\tsize = param[0]\n\t}\n\tbytes := make([]byte, size)\n\t_, err := BytesGenerator(bytes)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tid := make([]byte, size)\n\tfor i := 0; i < size; i++ {\n\t\tid[i] = defaultAlphabet[bytes[i]&63]\n\t}\n\treturn string(id[:size]), nil\n}", "func New64WithSeed(seed uint64) *Digest64 {\n\treturn (*Digest64)(New128WithSeed(seed, seed))\n}", "func (r *Rand) Uint64() uint64 {\n\t*r ^= Rand(uint64(*r) >> 12)\n\t*r ^= Rand(uint64(*r) << 25)\n\t*r ^= Rand(uint64(*r) >> 27)\n\treturn uint64(*r) * 2685821657736338717\n}", "func (f *Form) Uint64(param string, defaultValue uint64) uint64 {\n\tvals, ok := f.values[param]\n\tif !ok {\n\t\treturn defaultValue\n\t}\n\tparamVal, err := strconv.ParseUint(vals[0], 10, 64)\n\tif err != nil {\n\t\tf.err = err\n\t\treturn defaultValue\n\t}\n\treturn paramVal\n}", "func Uint64(input []byte, startBitPos int) (result uint64, resultPtr *uint64, err error) {\n\tif Len(input)-startBitPos < 64 {\n\t\treturn 0, nil, errors.New(\"Input is less than 64 bits\")\n\t}\n\n\ttmpArr, _, err := SubBits(input, startBitPos, 64)\n\tresult = binary.BigEndian.Uint64(tmpArr)\n\n\treturn result, &result, err\n}", "func (c *Config) GetUint64(pattern string, def ...interface{}) uint64 {\n\tif j := c.getJson(); j != nil {\n\t\treturn j.GetUint64(pattern, def...)\n\t}\n\treturn 0\n}", "func (c UintCodec) New() unsafe.Pointer {\n\treturn unsafe.Pointer(new(uint))\n}", "func Uint64(val interface{}) uint64 {\r\n\r\n\tswitch t := val.(type) {\r\n\tcase int:\r\n\t\treturn uint64(t)\r\n\tcase int8:\r\n\t\treturn uint64(t)\r\n\tcase int16:\r\n\t\treturn uint64(t)\r\n\tcase int32:\r\n\t\treturn uint64(t)\r\n\tcase int64:\r\n\t\treturn uint64(t)\r\n\tcase uint:\r\n\t\treturn uint64(t)\r\n\tcase uint8:\r\n\t\treturn uint64(t)\r\n\tcase uint16:\r\n\t\treturn uint64(t)\r\n\tcase uint32:\r\n\t\treturn uint64(t)\r\n\tcase uint64:\r\n\t\treturn uint64(t)\r\n\tcase float32:\r\n\t\treturn uint64(t)\r\n\tcase float64:\r\n\t\treturn uint64(t)\r\n\tcase bool:\r\n\t\tif t == true {\r\n\t\t\treturn uint64(1)\r\n\t\t}\r\n\t\treturn uint64(0)\r\n\tdefault:\r\n\t\ts := String(val)\r\n\t\ti, _ := strconv.ParseUint(s, 10, 64)\r\n\t\treturn i\r\n\t}\r\n\r\n\tpanic(\"Reached\")\r\n\r\n}" ]
[ "0.78732526", "0.7719561", "0.7704975", "0.75963604", "0.75139385", "0.73335713", "0.7065201", "0.69081914", "0.6897038", "0.6895006", "0.6835414", "0.679808", "0.6780824", "0.6757169", "0.67129046", "0.6652362", "0.65899986", "0.65518826", "0.6498531", "0.6391094", "0.63601905", "0.6358408", "0.6328706", "0.6294023", "0.6281588", "0.6245674", "0.6243125", "0.6219799", "0.6219799", "0.6219799", "0.6200128", "0.6189401", "0.61795473", "0.617936", "0.61450696", "0.6122898", "0.6122843", "0.6109659", "0.6095476", "0.6084508", "0.6084508", "0.6072288", "0.6063395", "0.6061887", "0.6053008", "0.6032076", "0.6003062", "0.598464", "0.5952895", "0.5936909", "0.593509", "0.5934052", "0.5934036", "0.5925494", "0.5922329", "0.58454585", "0.5845201", "0.5835321", "0.5832033", "0.58233404", "0.581233", "0.58053005", "0.57914317", "0.57876575", "0.57679105", "0.5747308", "0.5695887", "0.5693002", "0.5680351", "0.5673168", "0.5656887", "0.56364256", "0.56207734", "0.56205714", "0.56205714", "0.5614209", "0.5609516", "0.5602703", "0.5589012", "0.55815244", "0.5579713", "0.5579118", "0.5575718", "0.5571115", "0.5557104", "0.55544806", "0.5553747", "0.5552259", "0.55460966", "0.5543515", "0.5541354", "0.5539374", "0.5539201", "0.5530275", "0.5520227", "0.55163693", "0.5507413", "0.55030245", "0.5500815", "0.54991364" ]
0.8665488
0
CloneUInt64Slice clones src to dst by calling Clone for each element in src. Panics if len(dst) < len(src).
CloneUInt64Slice клонирует src в dst, вызывая Clone для каждого элемента в src. Вызывает панику, если len(dst) < len(src).
func CloneUInt64Slice(dst, src []UInt64) { for i := range src { dst[i] = *src[i].Clone() } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CloneUInt8Slice(dst, src []UInt8) {\n\tfor i := range src {\n\t\tdst[i] = *src[i].Clone()\n\t}\n}", "func CloneImuSlice(dst, src []Imu) {\n\tfor i := range src {\n\t\tdst[i] = *src[i].Clone()\n\t}\n}", "func CloneFloat64Slice(dst, src []Float64) {\n\tfor i := range src {\n\t\tdst[i] = *src[i].Clone()\n\t}\n}", "func CloneUInt16MultiArraySlice(dst, src []UInt16MultiArray) {\n\tfor i := range src {\n\t\tdst[i] = *src[i].Clone()\n\t}\n}", "func Uint64Slice(src []*uint64) []uint64 {\n\tdst := make([]uint64, len(src))\n\tfor i := 0; i < len(src); i++ {\n\t\tif src[i] != nil {\n\t\t\tdst[i] = *(src[i])\n\t\t}\n\t}\n\treturn dst\n}", "func (es Int64DataPointSlice) CopyTo(dest Int64DataPointSlice) {\n\tnewLen := es.Len()\n\tif newLen == 0 {\n\t\t*dest.orig = []*otlpmetrics.Int64DataPoint(nil)\n\t\treturn\n\t}\n\toldLen := dest.Len()\n\tif newLen <= oldLen {\n\t\t(*dest.orig) = (*dest.orig)[:newLen]\n\t\tfor i, el := range *es.orig {\n\t\t\tnewInt64DataPoint(&el).CopyTo(newInt64DataPoint(&(*dest.orig)[i]))\n\t\t}\n\t\treturn\n\t}\n\torigs := make([]otlpmetrics.Int64DataPoint, newLen)\n\twrappers := make([]*otlpmetrics.Int64DataPoint, newLen)\n\tfor i, el := range *es.orig {\n\t\twrappers[i] = &origs[i]\n\t\tnewInt64DataPoint(&el).CopyTo(newInt64DataPoint(&wrappers[i]))\n\t}\n\t*dest.orig = wrappers\n}", "func Uint64PtrSlice(src []uint64) []*uint64 {\n\tdst := make([]*uint64, len(src))\n\tfor i := 0; i < len(src); i++ {\n\t\tdst[i] = &(src[i])\n\t}\n\treturn dst\n}", "func CutUint64(slice []uint64, i, j uint64) []uint64 {\n\treturn append(slice[:i], slice[j:]...)\n}", "func (ids IDSlice) Copy() IDSlice {\n\tn := len(ids)\n\tnewIds := make([]ID, n)\n\tcopy(newIds, ids)\n\treturn newIds\n}", "func Uint64SlicePtr(src []uint64) []*uint64 {\n\tdst := make([]*uint64, len(src))\n\tfor i := 0; i < len(src); i++ {\n\t\tdst[i] = &(src[i])\n\t}\n\treturn dst\n}", "func Int64Slice(src []*int64) []int64 {\n\tdst := make([]int64, len(src))\n\tfor i := 0; i < len(src); i++ {\n\t\tif src[i] != nil {\n\t\t\tdst[i] = *(src[i])\n\t\t}\n\t}\n\treturn dst\n}", "func NewFromUint64Slice(items []uint64) *SliceOfUint64 {\n\tslicy := &SliceOfUint64{items}\n\treturn slicy\n}", "func CloneTimeReferenceSlice(dst, src []TimeReference) {\n\tfor i := range src {\n\t\tdst[i] = *src[i].Clone()\n\t}\n}", "func Uint64(src []uint64) []uint64 {\n\tdst := make([]uint64, len(src))\n\tcopy(dst, src)\n\treturn dst\n}", "func Int64PtrSlice(src []int64) []*int64 {\n\tdst := make([]*int64, len(src))\n\tfor i := 0; i < len(src); i++ {\n\t\tdst[i] = &(src[i])\n\t}\n\treturn dst\n}", "func clone(dst, src *image.Gray) {\n\tif dst.Stride == src.Stride {\n\t\t// no need to correct stride, simply copy pixels.\n\t\tcopy(dst.Pix, src.Pix)\n\t\treturn\n\t}\n\t// need to correct stride.\n\tfor i := 0; i < src.Rect.Dy(); i++ {\n\t\tdstH := i * dst.Stride\n\t\tsrcH := i * src.Stride\n\t\tcopy(dst.Pix[dstH:dstH+dst.Stride], src.Pix[srcH:srcH+dst.Stride])\n\t}\n}", "func ucopy(dst, src uptr, size uintptr) {\n\telems := (*reflect.SliceHeader)(src).Len\n\tif elems == 0 {\n\t\treturn\n\t}\n\t// Access the slice's underlying data\n\tsrc = uptr((*reflect.SliceHeader)(src).Data)\n\tcopy(\n\t\t(*[math.MaxInt32]byte)(dst)[:uintptr(elems)*size],\n\t\t(*[math.MaxInt32]byte)(src)[:uintptr(elems)*size],\n\t)\n}", "func Int64SlicePtr(src []int64) []*int64 {\n\tdst := make([]*int64, len(src))\n\tfor i := 0; i < len(src); i++ {\n\t\tdst[i] = &(src[i])\n\t}\n\treturn dst\n}", "func (x *BigUInt) Copy() *BigUInt {\n\ty := &BigUInt{\n\t\tdata: make([]uint8, len(x.data)),\n\t}\n\tfor i, v := range x.data {\n\t\ty.data[i] = v\n\t}\n\treturn y\n}", "func CloneUnloadNode_ResponseSlice(dst, src []UnloadNode_Response) {\n\tfor i := range src {\n\t\tdst[i] = *src[i].Clone()\n\t}\n}", "func CloneProjectedMapSlice(dst, src []ProjectedMap) {\n\tfor i := range src {\n\t\tdst[i] = *src[i].Clone()\n\t}\n}", "func CloneLoadNode_ResponseSlice(dst, src []LoadNode_Response) {\n\tfor i := range src {\n\t\tdst[i] = *src[i].Clone()\n\t}\n}", "func ToUInt64Slice(v []byte) ([]uint64, error) {\n\tpacket, _, err := DecodeNodePacket(v)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !packet.IsSlice() {\n\t\treturn nil, fmt.Errorf(\"v not a slice: %v\", utils.FormatBytes(v))\n\t}\n\tresult := make([]uint64, 0)\n\tfor _, p := range packet.PrimitivePackets {\n\t\tv, _ := p.ToUInt64()\n\t\tresult = append(result, v)\n\t}\n\treturn result, nil\n}", "func TakeUint64Ptr(n int, list []*uint64) []*uint64 {\n\tif n < 0 {\n\t\treturn []*uint64{}\n\t}\n\n\tnewListLen := len(list)\n\n\tif n < newListLen {\n\t\tnewListLen = n\n\t}\n\tnewList := make([]*uint64, newListLen)\n\tfor i := 0; i < newListLen; i++ {\n\t\tnewList[i] = list[i]\n\t}\n\treturn newList\n}", "func DeleteUint64(slice []uint64, sep uint64) []uint64 {\n\treturn append(slice[:sep], slice[sep+1:]...)\n}", "func TakeUint64(n int, list []uint64) []uint64 {\n\tif n < 0 {\n\t\treturn []uint64{}\n\t}\n\n\tnewListLen := len(list)\n\n\tif n < newListLen {\n\t\tnewListLen = n\n\t}\n\tnewList := make([]uint64, newListLen)\n\tfor i := 0; i < newListLen; i++ {\n\t\tnewList[i] = list[i]\n\t}\n\treturn newList\n}", "func slicecopy(toPtr unsafe.Pointer, toLen int, fromPtr unsafe.Pointer, fromLen int, width uintptr) int {\n\tif fromLen == 0 || toLen == 0 {\n\t\treturn 0\n\t}\n\n\tn := fromLen\n\tif toLen < n {\n\t\tn = toLen\n\t}\n\n\tif width == 0 {\n\t\treturn n\n\t}\n\n\tsize := uintptr(n) * width\n\tif raceenabled {\n\t\tcallerpc := getcallerpc()\n\t\tpc := funcPC(slicecopy)\n\t\tracereadrangepc(fromPtr, size, callerpc, pc)\n\t\tracewriterangepc(toPtr, size, callerpc, pc)\n\t}\n\tif msanenabled {\n\t\tmsanread(fromPtr, size)\n\t\tmsanwrite(toPtr, size)\n\t}\n\n\tif size == 1 { // common case worth about 2x to do here\n\t\t// TODO: is this still worth it with new memmove impl?\n\t\t*(*byte)(toPtr) = *(*byte)(fromPtr) // known to be a byte pointer\n\t} else {\n\t\tmemmove(toPtr, fromPtr, size)\n\t}\n\treturn n\n}", "func (ms *MySlice) Clone() Data {\n\tscopy := make([]int, len(ms.Slice))\n\tcopy(scopy, ms.Slice)\n\tmyslice := new(MySlice)\n\tmyslice.Slice = scopy\n\treturn Data(myslice)\n}", "func SortCopy(x []uint64) []uint64 {\n\ty := make([]uint64, len(x))\n\tcopy(y, x)\n\tSort(y)\n\treturn y\n}", "func memcpy(dst, src unsafe.Pointer, size uintptr)", "func (n *Int64Node) Copy() (n2 *Int64Node) {\n\tn2 = &Int64Node{Value: n.Value}\n\tif len(n.Children) == 0 {\n\t\treturn\n\t}\n\tn2.Children = make([]*Int64Node, len(n.Children))\n\tfor i, nx := range n.Children {\n\t\tif nx != nil {\n\t\t\tn2.Children[i] = nx.Copy()\n\t\t}\n\t}\n\treturn\n}", "func UnpackInt64(dst []int64, src []byte, bitWidth uint) {\n\t_ = src[:ByteCount(bitWidth*uint(len(dst))+8*PaddingInt64)]\n\tunpackInt64(dst, src, bitWidth)\n}", "func sliceUI64(in []byte) []uint64 {\n return (*(*[]uint64)(unsafe.Pointer(&in)))[:len(in)/8]\n}", "func (s Int64) Clone() Int64 {\n\treturn Int64(cast(s).Clone())\n}", "func CloneConfigLogger_ResponseSlice(dst, src []ConfigLogger_Response) {\n\tfor i := range src {\n\t\tdst[i] = *src[i].Clone()\n\t}\n}", "func (s Uint64Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }", "func ShiftUint64(slice []uint64) (uint64, []uint64) {\n\treturn slice[0], slice[1:]\n}", "func CloneTemperatureSlice(dst, src []Temperature) {\n\tfor i := range src {\n\t\tdst[i] = *src[i].Clone()\n\t}\n}", "func CloneMultiNestedSlice(dst, src []MultiNested) {\n\tfor i := range src {\n\t\tdst[i] = *src[i].Clone()\n\t}\n}", "func (dc *Int64DictConverter) Copy(out interface{}, vals []utils.IndexType) error {\n\to := out.([]int64)\n\tfor idx, val := range vals {\n\t\to[idx] = dc.dict[val]\n\t}\n\treturn nil\n}", "func CloneVector3StampedSlice(dst, src []Vector3Stamped) {\n\tfor i := range src {\n\t\tdst[i] = *src[i].Clone()\n\t}\n}", "func ClonePlaneSlice(dst, src []Plane) {\n\tfor i := range src {\n\t\tdst[i] = *src[i].Clone()\n\t}\n}", "func (s *syncMapInt64) copy(dst *syncMapInt64) {\n\tfor _, t := range s.keys() {\n\t\tdst.store(t, s.load(t))\n\t}\n}", "func (mm Uint64Uint64Map) Clone() Uint64Uint64Map {\n\tresult := NewUint64Uint64Map()\n\tfor k, v := range mm {\n\t\tresult[k] = v\n\t}\n\treturn result\n}", "func Copy(x, y Vector) {\n\tif x.N != y.N {\n\t\tpanic(badLength)\n\t}\n\tcblas128.Zcopy(x.N, x.Data, x.Inc, y.Data, y.Inc)\n}", "func UintSlice(src []*uint) []uint {\n\tdst := make([]uint, len(src))\n\tfor i := 0; i < len(src); i++ {\n\t\tif src[i] != nil {\n\t\t\tdst[i] = *(src[i])\n\t\t}\n\t}\n\treturn dst\n}", "func (set Int64Set) Clone() Int64Set {\n\tclonedSet := NewInt64Set()\n\tfor v := range set {\n\t\tclonedSet.doAdd(v)\n\t}\n\treturn clonedSet\n}", "func CloneWStringSlice(dst, src []WString) {\n\tfor i := range src {\n\t\tdst[i] = *src[i].Clone()\n\t}\n}", "func ToInt64Slice(v []byte) ([]int64, error) {\n\tpacket, _, err := DecodeNodePacket(v)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !packet.IsSlice() {\n\t\treturn nil, fmt.Errorf(\"v not a slice: %v\", utils.FormatBytes(v))\n\t}\n\tresult := make([]int64, 0)\n\tfor _, p := range packet.PrimitivePackets {\n\t\tv, _ := p.ToInt64()\n\t\tresult = append(result, v)\n\t}\n\treturn result, nil\n}", "func CopySlice(slice []byte) []byte {\n\tcopy := append(slice[:0:0], slice...)\n\treturn copy\n}", "func (bio *BinaryIO) Copy(dst int64, src int64, count int) error {\n\tbuf := makeBuf(count)\n\tfor count > 0 {\n\t\tbuf = truncBuf(buf, count)\n\t\tbio.ReadAt(src, buf)\n\t\tbio.WriteAt(dst, buf)\n\t\tcount -= len(buf)\n\t\tsrc += int64(len(buf))\n\t\tdst += int64(len(buf))\n\t}\n\treturn nil\n}", "func CloneKeyValueSlice(dst, src []KeyValue) {\n\tfor i := range src {\n\t\tdst[i] = *src[i].Clone()\n\t}\n}", "func cloneArray(source []int) []int {\n\tn := len(source)\n\tdestination := make([]int, n, n)\n\tcopy(source, destination)\n\treturn destination\n}", "func NewFromInt64Slice(items []int64) *SliceOfInt64 {\n\tslicy := &SliceOfInt64{items}\n\treturn slicy\n}", "func AppendUints64(dst []byte, vals []uint64) []byte {\n\tmajor := majorTypeArray\n\tl := len(vals)\n\tif l == 0 {\n\t\treturn AppendArrayEnd(AppendArrayStart(dst))\n\t}\n\tif l <= additionalMax {\n\t\tlb := byte(l)\n\t\tdst = append(dst, byte(major|lb))\n\t} else {\n\t\tdst = appendCborTypePrefix(dst, major, uint64(l))\n\t}\n\tfor _, v := range vals {\n\t\tdst = AppendUint64(dst, v)\n\t}\n\treturn dst\n}", "func emitCopyNoRepeat(dst []byte, offset, length int) int {\n\tif offset >= 65536 {\n\t\ti := 0\n\t\tif length > 64 {\n\t\t\t// Emit a length 64 copy, encoded as 5 bytes.\n\t\t\tdst[4] = uint8(offset >> 24)\n\t\t\tdst[3] = uint8(offset >> 16)\n\t\t\tdst[2] = uint8(offset >> 8)\n\t\t\tdst[1] = uint8(offset)\n\t\t\tdst[0] = 63<<2 | tagCopy4\n\t\t\tlength -= 64\n\t\t\tif length >= 4 {\n\t\t\t\t// Emit remaining as repeats\n\t\t\t\treturn 5 + emitCopyNoRepeat(dst[5:], offset, length)\n\t\t\t}\n\t\t\ti = 5\n\t\t}\n\t\tif length == 0 {\n\t\t\treturn i\n\t\t}\n\t\t// Emit a copy, offset encoded as 4 bytes.\n\t\tdst[i+0] = uint8(length-1)<<2 | tagCopy4\n\t\tdst[i+1] = uint8(offset)\n\t\tdst[i+2] = uint8(offset >> 8)\n\t\tdst[i+3] = uint8(offset >> 16)\n\t\tdst[i+4] = uint8(offset >> 24)\n\t\treturn i + 5\n\t}\n\n\t// Offset no more than 2 bytes.\n\tif length > 64 {\n\t\t// Emit a length 60 copy, encoded as 3 bytes.\n\t\t// Emit remaining as repeat value (minimum 4 bytes).\n\t\tdst[2] = uint8(offset >> 8)\n\t\tdst[1] = uint8(offset)\n\t\tdst[0] = 59<<2 | tagCopy2\n\t\tlength -= 60\n\t\t// Emit remaining as repeats, at least 4 bytes remain.\n\t\treturn 3 + emitCopyNoRepeat(dst[3:], offset, length)\n\t}\n\tif length >= 12 || offset >= 2048 {\n\t\t// Emit the remaining copy, encoded as 3 bytes.\n\t\tdst[2] = uint8(offset >> 8)\n\t\tdst[1] = uint8(offset)\n\t\tdst[0] = uint8(length-1)<<2 | tagCopy2\n\t\treturn 3\n\t}\n\t// Emit the remaining copy, encoded as 2 bytes.\n\tdst[1] = uint8(offset)\n\tdst[0] = uint8(offset>>8)<<5 | uint8(length-4)<<2 | tagCopy1\n\treturn 2\n}", "func CloneMultiDOFJointTrajectoryPointSlice(dst, src []MultiDOFJointTrajectoryPoint) {\n\tfor i := range src {\n\t\tdst[i] = *src[i].Clone()\n\t}\n}", "func bytesFromUInt64(src uint64) []uint8 {\n\tres := make([]uint8, 0, 8) // allocates a slice with capacity 8 but size 0, which\n\t// will \"grow\" as needed, up to the size of a uint64\n\tacc := src\n\tfor acc != 0 {\n\t\tres = append(res, uint8(acc&0xFF)) // casts, like from 64 to 8 bit ints, are almost always explicit in golang\n\t\tacc >>= 8\n\t}\n\treturn res\n}", "func CloneSliceOfString(n []string) []string {\n\tres := make([]string, 0, len(n))\n\tcopy(res, n)\n\treturn res\n}", "func MarshalVarUint64s(dst []byte, us []uint64) []byte {\n\tfor _, u := range us {\n\t\tif u < 0x80 {\n\t\t\t// Fast path\n\t\t\tdst = append(dst, byte(u))\n\t\t\tcontinue\n\t\t}\n\t\tfor u > 0x7f {\n\t\t\tdst = append(dst, 0x80|byte(u))\n\t\t\tu >>= 7\n\t\t}\n\t\tdst = append(dst, byte(u))\n\t}\n\treturn dst\n}", "func Copy(input []float64) []float64 {\n\toutput := make([]float64, len(input))\n\tcopy(output, input)\n\treturn output\n}", "func Slice_uint64_CTor() CGoHandle {\n\treturn CGoHandle(handleFromPtr_Slice_uint64(&[]uint64{}))\n}", "func UnshiftUint64(sep uint64, i []uint64) []uint64 {\n\treturn append([]uint64{sep}, i...)\n}", "func copy2DSlice(sourceSlice [][]byte, destinationSlice [][]byte) {\n\tfor i := 0; i < len(sourceSlice); i++ {\n\t\tfor j := 0; j < len(sourceSlice[i]); j++ {\n\t\t\tdestinationSlice[i][j] = sourceSlice[i][j]\n\t\t}\n\t}\n}", "func GetUint64s(size int) *Uint64s {\n\tv := uint64sPool.Get()\n\tif v == nil {\n\t\treturn &Uint64s{\n\t\t\tA: make([]uint64, size),\n\t\t}\n\t}\n\tis := v.(*Uint64s)\n\tif n := size - cap(is.A); n > 0 {\n\t\tis.A = append(is.A[:cap(is.A)], make([]uint64, n)...)\n\t}\n\tis.A = is.A[:size]\n\treturn is\n}", "func UnmarshalVarInt64s(dst []int64, src []byte) ([]byte, error) {\n\tidx := uint(0)\n\tfor i := range dst {\n\t\tif idx >= uint(len(src)) {\n\t\t\treturn nil, fmt.Errorf(\"cannot unmarshal varint from empty data\")\n\t\t}\n\t\tc := src[idx]\n\t\tidx++\n\t\tif c < 0x80 {\n\t\t\t// Fast path\n\t\t\tv := int8(c>>1) ^ (int8(c<<7) >> 7) // zig-zag decoding without branching.\n\t\t\tdst[i] = int64(v)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Slow path\n\t\tu := uint64(c & 0x7f)\n\t\tstartIdx := idx - 1\n\t\tshift := uint8(0)\n\t\tfor c >= 0x80 {\n\t\t\tif idx >= uint(len(src)) {\n\t\t\t\treturn nil, fmt.Errorf(\"unexpected end of encoded varint at byte %d; src=%x\", idx-startIdx, src[startIdx:])\n\t\t\t}\n\t\t\tif idx-startIdx > 9 {\n\t\t\t\treturn src[idx:], fmt.Errorf(\"too long encoded varint; the maximum allowed length is 10 bytes; got %d bytes; src=%x\",\n\t\t\t\t\t(idx-startIdx)+1, src[startIdx:])\n\t\t\t}\n\t\t\tc = src[idx]\n\t\t\tidx++\n\t\t\tshift += 7\n\t\t\tu |= uint64(c&0x7f) << shift\n\t\t}\n\t\tv := int64(u>>1) ^ (int64(u<<63) >> 63) // zig-zag decoding without branching.\n\t\tdst[i] = v\n\t}\n\treturn src[idx:], nil\n}", "func MarshalVarInt64s(dst []byte, vs []int64) []byte {\n\tfor _, v := range vs {\n\t\tif v < 0x40 && v > -0x40 {\n\t\t\t// Fast path\n\t\t\tc := int8(v)\n\t\t\tv := (c << 1) ^ (c >> 7) // zig-zag encoding without branching.\n\t\t\tdst = append(dst, byte(v))\n\t\t\tcontinue\n\t\t}\n\n\t\tv = (v << 1) ^ (v >> 63) // zig-zag encoding without branching.\n\t\tu := uint64(v)\n\t\tfor u > 0x7f {\n\t\t\tdst = append(dst, 0x80|byte(u))\n\t\t\tu >>= 7\n\t\t}\n\t\tdst = append(dst, byte(u))\n\t}\n\treturn dst\n}", "func BenchmarkDupSet64(b *testing.B) {\n\tdupInit(b)\n\tfor n := 0; n < b.N; n++ {\n\t\tdupIntSet64Data.Dup()\n\t}\n}", "func TakeInt64Ptr(n int, list []*int64) []*int64 {\n\tif n < 0 {\n\t\treturn []*int64{}\n\t}\n\n\tnewListLen := len(list)\n\n\tif n < newListLen {\n\t\tnewListLen = n\n\t}\n\tnewList := make([]*int64, newListLen)\n\tfor i := 0; i < newListLen; i++ {\n\t\tnewList[i] = list[i]\n\t}\n\treturn newList\n}", "func (s *Uint64) Slice() []uint64 {\n\tres := make([]uint64, 0, len(s.m))\n\n\tfor val := range s.m {\n\t\tres = append(res, val)\n\t}\n\treturn res\n}", "func Copy(dst Mutable, src Const) {\n\tif err := errIfDimsNotEq(src, dst); err != nil {\n\t\tpanic(err)\n\t}\n\n\tm, n := src.Dims()\n\tfor i := 0; i < m; i++ {\n\t\tfor j := 0; j < n; j++ {\n\t\t\tdst.Set(i, j, src.At(i, j))\n\t\t}\n\t}\n}", "func dedupInt64s(s []int64) []int64 {\n\tp := len(s) - 1\n\tif p <= 0 {\n\t\treturn s\n\t}\n\n\tfor i := p - 1; i >= 0; i-- {\n\t\tif s[p] != s[i] {\n\t\t\tp--\n\t\t\ts[p] = s[i]\n\t\t}\n\t}\n\n\treturn s[p:]\n}", "func copySlice(a []byte) []byte {\n\trv := make([]byte, len(a))\n\tcopy(rv, a)\n\treturn rv\n}", "func ReversedUint64(slice []uint64) []uint64 {\n\tfor left, right := 0, len(slice)-1; left < right; left, right = left+1, right-1 {\n\t\tslice[left], slice[right] = slice[right], slice[left]\n\t}\n\treturn slice\n}", "func (s *SliceOfUint64) Unshift(item uint64) *SliceOfUint64 {\n\ts.items = append([]uint64{item}, s.items...)\n\treturn s\n}", "func CloneGetAvailableStates_ResponseSlice(dst, src []GetAvailableStates_Response) {\n\tfor i := range src {\n\t\tdst[i] = *src[i].Clone()\n\t}\n}", "func (c *SequenceClockImpl) clone() SequenceClockImpl {\n\tcopy := SequenceClockImpl{\n\t\tvalue: make([]uint64, KMaxVbNo),\n\t\tcas: c.cas,\n\t}\n\n\tfor k, v := range c.value {\n\t\tcopy.value[k] = v\n\t}\n\treturn copy\n}", "func UnmarshalVarUint64s(dst []uint64, src []byte) ([]byte, error) {\n\tidx := uint(0)\n\tfor i := range dst {\n\t\tif idx >= uint(len(src)) {\n\t\t\treturn nil, fmt.Errorf(\"cannot unmarshal varuint from empty data\")\n\t\t}\n\t\tc := src[idx]\n\t\tidx++\n\t\tif c < 0x80 {\n\t\t\t// Fast path\n\t\t\tdst[i] = uint64(c)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Slow path\n\t\tu := uint64(c & 0x7f)\n\t\tstartIdx := idx - 1\n\t\tshift := uint8(0)\n\t\tfor c >= 0x80 {\n\t\t\tif idx >= uint(len(src)) {\n\t\t\t\treturn nil, fmt.Errorf(\"unexpected end of encoded varint at byte %d; src=%x\", idx-startIdx, src[startIdx:])\n\t\t\t}\n\t\t\tif idx-startIdx > 9 {\n\t\t\t\treturn src[idx:], fmt.Errorf(\"too long encoded varint; the maximum allowed length is 10 bytes; got %d bytes; src=%x\",\n\t\t\t\t\t(idx-startIdx)+1, src[startIdx:])\n\t\t\t}\n\t\t\tc = src[idx]\n\t\t\tidx++\n\t\t\tshift += 7\n\t\t\tu |= uint64(c&0x7f) << shift\n\t\t}\n\t\tdst[i] = u\n\t}\n\treturn src[idx:], nil\n}", "func Clone(in []string) (out []string) {\n\tout = make([]string, len(in))\n\tcopy(out, in)\n\treturn\n}", "func (s *SliceOfUint64) Shift() *SliceOfUint64 {\n\ts.items = s.items[1:]\n\treturn s\n}", "func copyIntSlice(s []int) []int {\n\tcopy := []int{}\n\tfor _, item := range s {\n\t\tcopy = append(copy, item)\n\t}\n\treturn copy\n}", "func (s *SliceOfUint64) Concat(items []uint64) *SliceOfUint64 {\n\ts.items = append(s.items, items...)\n\treturn s\n}", "func CloneNodeEntitiesInfoSlice(dst, src []NodeEntitiesInfo) {\n\tfor i := range src {\n\t\tdst[i] = *src[i].Clone()\n\t}\n}", "func MarshalVarUint64(dst []byte, u uint64) []byte {\n\tvar tmp [1]uint64\n\ttmp[0] = u\n\treturn MarshalVarUint64s(dst, tmp[:])\n}", "func CopyMem(source uint64, dest uint64, size uint64)", "func (x Vector64) Clone() Vector64 {\n\tcloneX := make(Vector64, len(x))\n\tcopy(cloneX, x)\n\treturn cloneX\n}", "func Int64(src []int64) []int64 {\n\tdst := make([]int64, len(src))\n\tcopy(dst, src)\n\treturn dst\n}", "func CycleUint64(s []uint64) <-chan uint64 {\n\tch := make(chan uint64, 1)\n\tgo func() {\n\t\tfor i := 0;; i++ {\n\t\t\tch <- s[i%len(s)]\n\t\t}\n\t}()\n\treturn ch\n}", "func UintPtrSlice(src []uint) []*uint {\n\tdst := make([]*uint, len(src))\n\tfor i := 0; i < len(src); i++ {\n\t\tdst[i] = &(src[i])\n\t}\n\treturn dst\n}", "func loadPrefixSafe(dst []byte, src []uint64, length int) ([]byte, int) {\n\t// prefix is stored as 8-byte multiples (uint64)\n\tvar (\n\t\tslots int\n\t\tdl int\n\t)\n\tif length == 255 {\n\t\t// prefixLen == 255 means it's >= 255, the real length is for simplicity stored in the next 8 byte slot (the unsafe version uses only 2 bytes for length)\n\t\tlength = int(src[0])\n\t\tslots = (length + 7) >> 3\n\t\tdl = slots << 3\n\t\tsrc = src[1 : slots+1]\n\t\tslots++\n\t} else {\n\t\tslots = (length + 7) >> 3\n\t\tdl = slots << 3\n\t\tsrc = src[:slots]\n\t}\n\t// fix size of dst\n\tif cap(dst) >= dl {\n\t\tdst = dst[:dl]\n\t} else {\n\t\tdst = make([]byte, dl)\n\t}\n\tk := 0\n\tfor _, a := range src {\n\t\t//binary.BigEndian.PutUint64(dst[k:k+8], a)\n\t\tfor j := 7; j >= 0; j-- {\n\t\t\tdst[k+j] = byte(a)\n\t\t\ta = a >> 8\n\t\t}\n\t\tk += 8\n\t}\n\treturn dst[:length], slots\n}", "func (ms Int64DataPoint) CopyTo(dest Int64DataPoint) {\n\tif ms.IsNil() {\n\t\t*dest.orig = nil\n\t\treturn\n\t}\n\tif dest.IsNil() {\n\t\tdest.InitEmpty()\n\t}\n\tms.LabelsMap().CopyTo(dest.LabelsMap())\n\tdest.SetStartTime(ms.StartTime())\n\tdest.SetTimestamp(ms.Timestamp())\n\tdest.SetValue(ms.Value())\n}", "func CloneSliceOfColIdent(n []ColIdent) []ColIdent {\n\tres := make([]ColIdent, 0, len(n))\n\tfor _, x := range n {\n\t\tres = append(res, CloneColIdent(x))\n\t}\n\treturn res\n}", "func CloneLV(ctx context.Context, src, dest string) (string, error) {\n\t// FIXME(farcaller): bloody insecure. And broken.\n\tsp, _ := opentracing.StartSpanFromContext(ctx, \"sys.dd\")\n\tsp.SetTag(\"component\", \"dd\")\n\tsp.SetTag(\"span.kind\", \"client\")\n\tdefer sp.Finish()\n\n\tcmd := exec.Command(\"dd\", fmt.Sprintf(\"if=%s\", src), fmt.Sprintf(\"of=%s\", dest), \"bs=4M\")\n\tout, err := cmd.CombinedOutput()\n\treturn string(out), err\n}", "func CloneJoyFeedbackSlice(dst, src []JoyFeedback) {\n\tfor i := range src {\n\t\tdst[i] = *src[i].Clone()\n\t}\n}", "func CopyN(in chan int,\n\tout []chan int) {\n\tl := len(out)\n\tvar i, v int = 0, 0\n\tfor {\n\t\ti = 0\n\t\tv = <-in\n\t\tfor i < l {\n\t\t\tgo SendValue(v, out[i])\n\t\t\ti = i + 1\n\t\t}\n\t}\n}", "func CloneUpdateFilename_RequestSlice(dst, src []UpdateFilename_Request) {\n\tfor i := range src {\n\t\tdst[i] = *src[i].Clone()\n\t}\n}", "func InsertUint64(slice []uint64, element, position uint64) []uint64 {\n\treturn append(slice[:position], append([]uint64{element}, slice[position:]...)...)\n}", "func FromUint64(buffer [][]uint64, startRow, startCol, rows, cols int) ([][]uint64, error) {\n\tview := make([][]uint64, rows)\n\tif len(buffer) < startRow+rows {\n\t\treturn nil, fmt.Errorf(\"matrix has less rows than asked: %d x %d\", len(buffer), startRow+rows)\n\t}\n\tfor i := range view {\n\t\tif len(buffer[startRow+i]) < startCol+cols {\n\t\t\treturn nil, fmt.Errorf(\"row %d has less cols than asked: %d x %d\", i, len(buffer[startRow+i]), startCol+cols)\n\t\t}\n\t\tview[i] = buffer[startRow+i][startCol : startCol+cols : startCol+cols]\n\t}\n\treturn view, nil\n}", "func (pu *ProxyUser) DeepClone() *ProxyUser {\n\tif pu == nil {\n\t\treturn nil\n\t}\n\tcloned := ProxyUser{}\n\tcloned = *pu\n\tcloned.StorageArrayIdentifiers = make([]string, len(pu.StorageArrayIdentifiers))\n\tcopy(cloned.StorageArrayIdentifiers, pu.StorageArrayIdentifiers)\n\treturn &cloned\n}", "func UnmarshalVarInt64(src []byte) ([]byte, int64, error) {\n\tvar tmp [1]int64\n\ttail, err := UnmarshalVarInt64s(tmp[:], src)\n\treturn tail, tmp[0], err\n}" ]
[ "0.6897268", "0.6507103", "0.6395663", "0.6381664", "0.61048645", "0.56997764", "0.5694446", "0.5657911", "0.5633476", "0.5577525", "0.55724555", "0.5572285", "0.5505419", "0.54988307", "0.5482363", "0.54418826", "0.5430907", "0.54308385", "0.5412383", "0.5385675", "0.52670246", "0.52437174", "0.52430093", "0.52284443", "0.5216756", "0.52140087", "0.5201792", "0.52011716", "0.5183444", "0.51328856", "0.5126937", "0.51168275", "0.5083611", "0.5059875", "0.50524676", "0.50518334", "0.5039812", "0.50249434", "0.50227284", "0.50227165", "0.50058264", "0.499699", "0.4986518", "0.4964682", "0.49377447", "0.4913171", "0.491036", "0.48759407", "0.48722032", "0.48523787", "0.48477834", "0.48308653", "0.48225892", "0.48192272", "0.4819107", "0.48166788", "0.4816673", "0.48156342", "0.480842", "0.47905096", "0.47895828", "0.47837487", "0.4783734", "0.4772127", "0.47621548", "0.47574523", "0.47568563", "0.47554728", "0.47549108", "0.47427493", "0.47411942", "0.47381243", "0.47353372", "0.47281605", "0.4710484", "0.47084403", "0.47081566", "0.4706102", "0.4703069", "0.47022346", "0.46855205", "0.4684928", "0.46823326", "0.46814775", "0.4674469", "0.4667699", "0.46659106", "0.4656125", "0.46541262", "0.46524563", "0.46322483", "0.46270362", "0.46166342", "0.46124965", "0.46036658", "0.45895413", "0.45879254", "0.45843855", "0.457561", "0.45749673" ]
0.83064985
0
GetEcsServiceConfig returns config for aws_ecs_service
GetEcsServiceConfig возвращает конфиг для aws_ecs_service
func GetEcsServiceConfig(c *ecs.Service) []AWSResourceConfig { cf := EcsServiceConfig{ Config: Config{ Name: c.ServiceName, Tags: c.Tags, }, IamRole: c.Role, } return []AWSResourceConfig{{ Resource: cf, Metadata: c.AWSCloudFormationMetadata, }} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetServiceConfig(req *restful.Request, resp *restful.Response) {\n\tconst (\n\t\thandler = \"GetServiceConfig\"\n\t)\n\tspan := v1http.SetHTTPSpanContextInfo(req, handler)\n\tdefer span.Finish()\n\n\tr, err := generateData(req, getMultiCls)\n\tif err != nil {\n\t\tutils.SetSpanLogTagError(span, err)\n\t\tblog.Errorf(\"%s | err: %v\", common.BcsErrStorageGetResourceFailStr, err)\n\t\tlib.ReturnRest(&lib.RestResponse{\n\t\t\tResp: resp,\n\t\t\tErrCode: common.BcsErrStorageGetResourceFail,\n\t\t\tMessage: common.BcsErrStorageGetResourceFailStr})\n\t\treturn\n\t}\n\tlib.ReturnRest(&lib.RestResponse{Resp: resp, Data: r})\n}", "func (configProvider) GetServiceConfig(c context.Context) (*tricium.ServiceConfig, error) {\n\treturn getServiceConfig(c)\n}", "func getConfig() (aws.Config, error) {\n\tif os.Getenv(\"AWS_REGION\") == \"\" {\n\t\treturn aws.Config{}, errors.New(\"AWS_REGION is not set\")\n\t}\n\n\tvar cfg aws.Config\n\tvar err error\n\n\tif awsEndpoint := os.Getenv(\"CUSTOM_AWS_ENDPOINT_URL\"); awsEndpoint != \"\" {\n\t\tcustomResolver := aws.EndpointResolverWithOptionsFunc(func(service, region string, options ...interface{}) (aws.Endpoint, error) {\n\t\t\treturn aws.Endpoint{\n\t\t\t\tPartitionID: \"aws\",\n\t\t\t\tURL: awsEndpoint,\n\t\t\t}, nil\n\t\t})\n\n\t\tcfg, err = config.LoadDefaultConfig(\n\t\t\tcontext.TODO(),\n\t\t\tconfig.WithEndpointResolverWithOptions(customResolver))\n\t} else {\n\t\tcfg, err = config.LoadDefaultConfig(context.TODO())\n\t}\n\n\tif err != nil {\n\t\treturn aws.Config{}, err\n\t}\n\treturn cfg, nil\n}", "func (mockProvider) GetServiceConfig(c context.Context) (*tricium.ServiceConfig, error) {\n\treturn &tricium.ServiceConfig{}, nil\n}", "func GetEsConfig(key string) ConfigEs {\n\tvar conf ConfigEs\n\tconf.Addr = GetString(key + \".\" + \"addr\")\n\tconf.UserName = GetString(key + \".\" + \"userName\")\n\tconf.Password = GetString(key + \".\" + \"password\")\n\tconf.TimeOutMs = GetUInt32(key + \".\" + \"timeOutMs\")\n\n\treturn conf\n}", "func (s *server) GetServiceConfig(ctx context.Context, _ *transactionpb.GetServiceConfigRequest) (*transactionpb.GetServiceConfigResponse, error) {\n\tsubsidizer := s.subsidizer.Public().(ed25519.PublicKey)\n\n\tappIndex, _ := app.GetAppIndex(ctx)\n\tif appIndex > 0 {\n\t\tcfg, err := s.appConfig.Get(ctx, appIndex)\n\t\tif err != nil && err != app.ErrNotFound {\n\t\t\treturn nil, status.Error(codes.Internal, \"failed to get app config\")\n\t\t} else if err == nil && cfg.Subsidizer != nil {\n\t\t\tsubsidizer = cfg.Subsidizer\n\t\t}\n\t}\n\n\treturn &transactionpb.GetServiceConfigResponse{\n\t\tToken: &commonpb.SolanaAccountId{\n\t\t\tValue: s.token,\n\t\t},\n\t\tTokenProgram: &commonpb.SolanaAccountId{\n\t\t\tValue: token.ProgramKey,\n\t\t},\n\t\tSubsidizerAccount: &commonpb.SolanaAccountId{\n\t\t\tValue: subsidizer,\n\t\t},\n\t}, nil\n}", "func (r *AppConfig) GetServiceConfig(sName string) CommonServiceConfig {\n\tsCfg, _ := r.ServiceConfig[sName]\n\n\treturn sCfg\n}", "func (s *Service) ServiceConfig() *registry.ServiceConfig {\n\ts.mu.RLock()\n\tdefer s.mu.RUnlock()\n\treturn s.config.copy()\n}", "func GetKubeConfig(clusterName string, region string) (*rest.Config, error) {\n\tif clusterName == \"\" {\n\t\terr := errors.New(\"Cluster name is required\")\n\t\tlog.Error().Err(err).Msg(\"Failed to create kube client\")\n\t\treturn nil, err\n\t}\n\n\tif region == \"\" {\n\t\terr := errors.New(\"Region is required\")\n\t\tlog.Error().Err(err).Msg(\"Failed to create kube client\")\n\t\treturn nil, err\n\t}\n\n\ts, err := session.NewSession(&aws.Config{Region: aws.String(region)})\n\tsvc := eks.New(s)\n\tinput := &eks.DescribeClusterInput{\n\t\tName: aws.String(clusterName),\n\t}\n\n\tclusterInfo, err := svc.DescribeCluster(input)\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tlog.Error().Err(aerr).Str(\"code\", aerr.Code()).Msg(\"Failed to describe cluster\")\n\t\t} else {\n\t\t\tlog.Error().Err(err).Msg(\"Failed to describe cluster\")\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tca, err := base64.StdEncoding.DecodeString(*clusterInfo.Cluster.CertificateAuthority.Data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tgen, err := token.NewGenerator(false, false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttkn, err := gen.Get(*clusterInfo.Cluster.Name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &rest.Config{\n\t\tHost: *clusterInfo.Cluster.Endpoint,\n\t\tBearerToken: tkn.Token,\n\t\tTLSClientConfig: rest.TLSClientConfig{\n\t\t\tCAData: ca,\n\t\t},\n\t}, nil\n}", "func (client *ApiECSClient) serviceClient() (*svc.AmazonEC2ContainerServiceV20141113Client, error) {\n\tconfig := client.config\n\n\tsigner := authv4.NewHttpSigner(config.AWSRegion, ECS_SERVICE, client.CredentialProvider(), nil)\n\n\tc := codec.AwsJson{Host: config.APIEndpoint, SignerV4: signer}\n\n\td, err := dialer.TLS(config.APIEndpoint, config.APIPort, &tls.Config{InsecureSkipVerify: client.insecureSkipVerify})\n\n\tif err != nil {\n\t\tlog.Error(\"Cannot resolve url\", \"url\", config.APIEndpoint, \"port\", config.APIPort, \"err\", err)\n\t\treturn nil, err\n\t}\n\n\tecs := svc.NewAmazonEC2ContainerServiceV20141113Client(d, c)\n\treturn ecs, nil\n}", "func (p *DNSProvider) GetConfig() *aws.Config {\n\tawsConfig := &aws.Config{\n\t\tRegion: aws.String(\"us-west-2\"),\n\t\tCredentials: credentials.NewStaticCredentials(p.AccessKey, p.SecretKey, \"\"),\n\t}\n\treturn awsConfig\n}", "func getConfig() (aws.Config, error) {\n\tif os.Getenv(\"AWS_REGION\") == \"\" {\n\t\treturn aws.Config{}, errors.New(\"AWS_REGION is not set\")\n\t}\n\tcfg, err := config.LoadDefaultConfig(context.TODO())\n\tif err != nil {\n\t\treturn aws.Config{}, err\n\t}\n\treturn cfg, nil\n}", "func (s *site) getEtcdConfig(ctx context.Context, opCtx *operationContext, server *ProvisionedServer) (*etcdConfig, error) {\n\tetcdClient, err := clients.DefaultEtcdMembers()\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\tmembers, err := etcdClient.List(ctx)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\tinitialCluster := []string{opCtx.provisionedServers.InitialCluster(s.domainName)}\n\t// add existing members\n\tfor _, member := range members {\n\t\taddress, err := utils.URLHostname(member.PeerURLs[0])\n\t\tif err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\tinitialCluster = append(initialCluster, fmt.Sprintf(\"%s:%s\",\n\t\t\tmember.Name, address))\n\t}\n\tproxyMode := etcdProxyOff\n\tif !server.IsMaster() {\n\t\tproxyMode = etcdProxyOn\n\t}\n\treturn &etcdConfig{\n\t\tinitialCluster: strings.Join(initialCluster, \",\"),\n\t\tinitialClusterState: etcdExistingCluster,\n\t\tproxyMode: proxyMode,\n\t}, nil\n}", "func (o FunctionOutput) ServiceConfig() ServiceConfigResponseOutput {\n\treturn o.ApplyT(func(v *Function) ServiceConfigResponseOutput { return v.ServiceConfig }).(ServiceConfigResponseOutput)\n}", "func GetHSSConfig() (*mconfig.HSSConfig, error) {\n\tserviceBaseName := filepath.Base(os.Args[0])\n\tserviceBaseName = strings.TrimSuffix(serviceBaseName, filepath.Ext(serviceBaseName))\n\tif hssServiceName != serviceBaseName {\n\t\tglog.Errorf(\n\t\t\t\"NOTE: HSS Service name: %s does not match its managed configs key: %s\\n\",\n\t\t\tserviceBaseName, hssServiceName)\n\t}\n\n\tconfigsPtr := &mconfig.HSSConfig{}\n\terr := configs.GetServiceConfigs(hssServiceName, configsPtr)\n\tif err != nil || configsPtr.Server == nil || configsPtr.DefaultSubProfile == nil {\n\t\tglog.Errorf(\"%s Managed Configs Load Error: %v\\n\", hssServiceName, err)\n\t\treturn &mconfig.HSSConfig{\n\t\t\tServer: &mconfig.DiamServerConfig{\n\t\t\t\tProtocol: diameter.GetValueOrEnv(diameter.NetworkFlag, ServerProtocol, hssDefaultProtocol),\n\t\t\t\tAddress: diameter.GetValueOrEnv(diameter.AddrFlag, ServerAddress, \"\"),\n\t\t\t\tLocalAddress: diameter.GetValueOrEnv(diameter.LocalAddrFlag, ServerLocalAddress, \"\"),\n\t\t\t\tDestHost: diameter.GetValueOrEnv(diameter.DestHostFlag, ServerDestHost, hssDefaultHost),\n\t\t\t\tDestRealm: diameter.GetValueOrEnv(diameter.DestRealmFlag, ServerDestRealm, hssDefaultRealm),\n\t\t\t},\n\t\t\tLteAuthOp: hssDefaultLteAuthOp,\n\t\t\tLteAuthAmf: hssDefaultLteAuthAmf,\n\t\t\tDefaultSubProfile: &mconfig.HSSConfig_SubscriptionProfile{\n\t\t\t\tMaxUlBitRate: diameter.GetValueUint64(maxUlBitRateFlag, defaultMaxUlBitRate),\n\t\t\t\tMaxDlBitRate: diameter.GetValueUint64(maxDlBitRateFlag, defaultMaxDlBitRate),\n\t\t\t},\n\t\t\tSubProfiles: make(map[string]*mconfig.HSSConfig_SubscriptionProfile),\n\t\t\tStreamSubscribers: *streamSubscribersFlag,\n\t\t}, err\n\t}\n\n\tglog.V(2).Infof(\"Loaded %s configs: %+v\\n\", hssServiceName, configsPtr)\n\treturn &mconfig.HSSConfig{\n\t\tServer: &mconfig.DiamServerConfig{\n\t\t\tAddress: diameter.GetValue(diameter.AddrFlag, configsPtr.Server.Address),\n\t\t\tProtocol: diameter.GetValue(diameter.NetworkFlag, configsPtr.Server.Protocol),\n\t\t\tLocalAddress: diameter.GetValue(diameter.LocalAddrFlag, configsPtr.Server.LocalAddress),\n\t\t\tDestHost: diameter.GetValue(diameter.DestHostFlag, configsPtr.Server.DestHost),\n\t\t\tDestRealm: diameter.GetValue(diameter.DestRealmFlag, configsPtr.Server.DestRealm),\n\t\t},\n\t\tLteAuthOp: configsPtr.LteAuthOp,\n\t\tLteAuthAmf: configsPtr.LteAuthAmf,\n\t\tDefaultSubProfile: &mconfig.HSSConfig_SubscriptionProfile{\n\t\t\tMaxUlBitRate: diameter.GetValueUint64(maxUlBitRateFlag, configsPtr.DefaultSubProfile.MaxUlBitRate),\n\t\t\tMaxDlBitRate: diameter.GetValueUint64(maxDlBitRateFlag, configsPtr.DefaultSubProfile.MaxDlBitRate),\n\t\t},\n\t\tSubProfiles: configsPtr.SubProfiles,\n\t\tStreamSubscribers: configsPtr.StreamSubscribers || *streamSubscribersFlag,\n\t}, nil\n}", "func (s *server) GetConfig(c context.Context, req *google.Empty) (*logdog.GetConfigResponse, error) {\n\tgcfg, err := coordinator.GetServices(c).Config(c)\n\tif err != nil {\n\t\tlog.Fields{\n\t\t\tlog.ErrorKey: err,\n\t\t}.Errorf(c, \"Failed to load configuration.\")\n\t\treturn nil, grpcutil.Internal\n\t}\n\n\treturn &logdog.GetConfigResponse{\n\t\tConfigServiceUrl: gcfg.ConfigServiceURL.String(),\n\t\tConfigSet: gcfg.ConfigSet,\n\t\tServiceConfigPath: gcfg.ServiceConfigPath,\n\t}, nil\n}", "func (s *Service) Config() *config.ServiceConfig {\n\treturn s.serviceConfig\n}", "func GetEndpointsConfig() []string {\n\tos.Setenv(\"ETCDCTL_API\", viper.GetString(\"Etcd.Api\"))\n\t//fmt.Println(\"ETCD Api version: \", os.Getenv(\"ETCDCTL_API\"))\n\tos.Setenv(\"ETCDCTL_ENDPOINTS\", viper.GetString(\"Etcd.Endpoints\"))\n\t//fmt.Println(\"ETCD ENDPOINTS: \", os.Getenv(\"ETCDCTL_ENDPOINTS\"))\n\tos.Setenv(\"ETCDCTL_CERT\", viper.GetString(\"Etcd.Cert\"))\n\t//fmt.Println(\"ETCD CERT: \", os.Getenv(\"ETCDCTL_CERT\"))\n\tos.Setenv(\"ETCDCTL_CACERT\", viper.GetString(\"Etcd.CaCert\"))\n\t//fmt.Println(\"ETCD CACERT: \", os.Getenv(\"ETCDCTL_CACERT\"))\n\tos.Setenv(\"ETCDCTL_KEY\", viper.GetString(\"Etcd.Key\"))\n\t//fmt.Println(\"ETCD KEY: \", os.Getenv(\"ETCDCTL_KEY\"))\n\treturn []string{(viper.GetViper().GetString(\"Etcd.Endpoints\"))}\n}", "func (s *Service) Config() *ServiceConfig {\n\treturn s.config\n}", "func (app *application) GetConfig() config.Instance {\n\tloadConfigOnce.Do(func() {\n\t\tconfigInstance := viper.New()\n\t\tconfigInstance.SetConfigName(\"service\")\n\t\tconfigInstance.AddConfigPath(\"./config\")\n\t\terr := configInstance.ReadInConfig()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tapp.config = configInstance\n\t})\n\treturn app.config\n}", "func (s Service) Config() *container.Config {\n\tconfig := s.ContainerConfig\n\tconfig.Image = s.ImageName()\n\treturn &config\n}", "func ConvertToECSNetworkConfiguration(ecsParams *ECSParams) (*ecs.NetworkConfiguration, error) {\n\tif ecsParams == nil {\n\t\treturn nil, nil\n\t}\n\n\tnetworkMode := ecsParams.TaskDefinition.NetworkMode\n\n\tif networkMode != \"awsvpc\" {\n\t\treturn nil, nil\n\t}\n\n\tawsvpcConfig := ecsParams.RunParams.NetworkConfiguration.AwsVpcConfiguration\n\n\tsubnets := awsvpcConfig.Subnets\n\n\tif len(subnets) < 1 {\n\t\treturn nil, errors.New(\"at least one subnet is required in the network configuration\")\n\t}\n\n\tsecurityGroups := awsvpcConfig.SecurityGroups\n\tassignPublicIp := string(awsvpcConfig.AssignPublicIp)\n\n\tecsSubnets := make([]*string, len(subnets))\n\tfor i, subnet := range subnets {\n\t\tecsSubnets[i] = aws.String(subnet)\n\t}\n\n\tecsSecurityGroups := make([]*string, len(securityGroups))\n\tfor i, sg := range securityGroups {\n\t\tecsSecurityGroups[i] = aws.String(sg)\n\t}\n\n\tecsAwsVpcConfig := &ecs.AwsVpcConfiguration{\n\t\tSubnets: ecsSubnets,\n\t\tSecurityGroups: ecsSecurityGroups,\n\t}\n\n\t// For tasks launched with network config in EC2 mode, assign_pubic_ip field is not accepted\n\tif assignPublicIp != \"\" {\n\t\tecsAwsVpcConfig.AssignPublicIp = aws.String(assignPublicIp)\n\t}\n\n\tecsNetworkConfig := &ecs.NetworkConfiguration{\n\t\tAwsvpcConfiguration: ecsAwsVpcConfig,\n\t}\n\n\treturn ecsNetworkConfig, nil\n}", "func (s *Service) Config() *svcconfig.Config {\n\treturn s.config.Config()\n}", "func (s *Services) Config() *Configuration { return &s.config }", "func (p *Provider) GetConfig() *aws.Config {\n\tawsConfig := &aws.Config{\n\t\tRegion: aws.String(p.Region),\n\t\tCredentials: credentials.NewStaticCredentials(p.AccessKey, p.SecretKey, \"\"),\n\t}\n\treturn awsConfig\n}", "func (p *EtcdClientV3) GetConfig() *ClientConfig {\n\treturn &ClientConfig{\n\t\tendpoints: p.endpoints,\n\t\tTLSConfig: p.tlsConfig,\n\t}\n}", "func getConfig() aws.Config {\n\tconfigMu.Lock()\n\tdefer configMu.Unlock()\n\n\tif cfg != nil {\n\t\treturn *cfg\n\t}\n\tc, err := config.LoadDefaultConfig(context.Background())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tcfg = &c\n\treturn *cfg\n}", "func getClusterConfig(inCluster bool) (*rest.Config, error) {\n\tif inCluster {\n\t\treturn rest.InClusterConfig()\n\t}\n\tconfigFile := getKubeConfigFile()\n\n\tif len(configFile) > 0 {\n\n\t\tlog.Infof(\"Reading config from file: %v\", configFile)\n\t\t// use the current context in kubeconfig\n\t\t// This is very useful for running locally.\n\t\tclientConfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(\n\t\t\t&clientcmd.ClientConfigLoadingRules{ExplicitPath: configFile},\n\t\t\t&clientcmd.ConfigOverrides{ClusterInfo: clientcmdapi.Cluster{Server: \"\"}})\n\n\t\trawConfig, err := clientConfig.RawConfig()\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif err := modifyGcloudCommand(&rawConfig); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tconfig, err := clientConfig.ClientConfig()\n\t\treturn config, err\n\t}\n\n\t// Work around https://github.com/kubernetes/kubernetes/issues/40973\n\t// See https://github.com/coreos/etcd-operator/issues/731#issuecomment-283804819\n\tif len(os.Getenv(\"KUBERNETES_SERVICE_HOST\")) == 0 {\n\t\taddrs, err := net.LookupHost(\"kubernetes.default.svc\")\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tif err := os.Setenv(\"KUBERNETES_SERVICE_HOST\", addrs[0]); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif len(os.Getenv(\"KUBERNETES_SERVICE_PORT\")) == 0 {\n\t\tif err := os.Setenv(\"KUBERNETES_SERVICE_PORT\", \"443\"); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tconfig, err := rest.InClusterConfig()\n\treturn config, err\n}", "func AWSCfg(ctx context.Context, accessKeyID, secretKey string) aws.Config {\n\topts := []func(*config.LoadOptions) error{\n\t\tconfig.WithRegion(\"us-west-1\"),\n\t}\n\n\t// In local environment we use the default credentials chain that\n\t// will automatically pull creds from saml2aws,\n\tif !Local {\n\t\topts = append(opts, config.WithCredentialsProvider(\n\t\t\tcredentials.NewStaticCredentialsProvider(accessKeyID, secretKey, \"\"),\n\t\t))\n\t}\n\n\tcfg, err := config.LoadDefaultConfig(ctx, opts...)\n\tif err != nil {\n\t\tfmt.Println(\"failed to load aws config:\", err)\n\t\tos.Exit(1)\n\t}\n\n\treturn cfg\n}", "func ReadECSParams(filename string) (*ECSParams, error) {\n\tif filename == \"\" {\n\t\tdefaultFilename := \"ecs-params.yml\"\n\t\tif _, err := os.Stat(defaultFilename); err == nil {\n\t\t\tfilename = defaultFilename\n\t\t} else {\n\t\t\treturn nil, nil\n\t\t}\n\t}\n\n\t// NOTE: Readfile reads all data into memory and closes file. Could\n\t// eventually refactor this to read different sections separately.\n\tecsParamsData, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"Error reading file '%v'\", filename)\n\t}\n\tecsParamsData = []byte(os.ExpandEnv(string(ecsParamsData)))\n\tecsParams := &ECSParams{}\n\n\tif err = yaml.Unmarshal([]byte(ecsParamsData), &ecsParams); err != nil {\n\t\treturn nil, errors.Wrapf(err, \"Error unmarshalling yaml data from ECS params file: %v\", filename)\n\t}\n\n\treturn ecsParams, nil\n}", "func (c *clustermgrClient) GetConfig(ctx context.Context, key string) (val string, err error) {\n\tc.rwLock.RLock()\n\tdefer c.rwLock.RUnlock()\n\n\tspan := trace.SpanFromContextSafe(ctx)\n\tret, err := c.client.GetConfig(ctx, key)\n\tif err != nil {\n\t\tspan.Errorf(\"get config failed: key[%s], err[%+v]\", key, err)\n\t\treturn\n\t}\n\treturn ret, err\n}", "func (p providerServices) EKS() eks.EKSer {\n\treturn p.eks\n}", "func GetEcsConnection(creds *credentials.Credentials, region string) *ecs.ECS {\n\treturn ecs.New(session.New(), &aws.Config{\n\t\tRegion: aws.String(region),\n\t\tCredentials: creds,\n\t})\n}", "func (k *KubernetesSpecification) getConfig(cnsiRecord *interfaces.CNSIRecord, tokenRecord *interfaces.TokenRecord) (*rest.Config, error) {\n\tmasterURL := cnsiRecord.APIEndpoint.String()\n\treturn k.GetConfigForEndpoint(masterURL, *tokenRecord)\n}", "func (o ClusterOutput) ServiceExternalIpsConfig() ClusterServiceExternalIpsConfigOutput {\n\treturn o.ApplyT(func(v *Cluster) ClusterServiceExternalIpsConfigOutput { return v.ServiceExternalIpsConfig }).(ClusterServiceExternalIpsConfigOutput)\n}", "func GetEdgegridConfig(c *cli.Context) (*edgegrid.Config, error) {\n\tedgercOps := []edgegrid.Option{\n\t\tedgegrid.WithEnv(true),\n\t\tedgegrid.WithFile(GetEdgercPath(c)),\n\t\tedgegrid.WithSection(GetEdgercSection(c)),\n\t}\n\tconfig, err := edgegrid.New(edgercOps...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif c.IsSet(\"accountkey\") {\n\t\tconfig.AccountKey = c.String(\"accountkey\")\n\t}\n\treturn config, nil\n}", "func (e *localExocomDependency) GetDockerConfig() (types.DockerConfig, error) {\n\tserviceRoutes, err := e.getServiceRoutesString()\n\tif err != nil {\n\t\treturn types.DockerConfig{}, err\n\t}\n\treturn types.DockerConfig{\n\t\tContainerName: e.GetContainerName(),\n\t\tImage: fmt.Sprintf(\"originate/exocom:%s\", e.config.Version),\n\t\tEnvironment: map[string]string{\n\t\t\t\"ROLE\": \"exocom\",\n\t\t\t\"SERVICE_ROUTES\": serviceRoutes,\n\t\t},\n\t\tRestart: \"on-failure\",\n\t}, nil\n}", "func getServiceConfig(cfg *CmdConfig) (KubeObjects, error) {\n\t// Intialize KubeObjects\n\tvar kubeObjects KubeObjects\n\tkubeObjects.ServiceInstances = make(map[string][]*catalogv1beta1.ServiceInstance)\n\tkubeObjects.ServiceBindings = make(map[string][]*catalogv1beta1.ServiceBinding)\n\tkubeObjects.IngressRouteList = new(contourv1beta1.IngressRouteList)\n\tkubeObjects.NamedSecrets = new(v1.SecretList)\n\n\t// Allowed names for kubernetes object files are deployment.yaml, service.yaml, and ingress.yaml,\n\t// or their environment specific variations.\n\t// Istio CustomResourceDefinitions should be in istio.yaml or the environment specific variation.\n\tpossibleFiles := []string{\n\t\t\"deployment\",\n\t\t\"service\",\n\t\t\"ingress\",\n\t\t\"istio\",\n\t\t\"job\",\n\t\t\"ethos-logging-sidecar\",\n\t\t\"servicecatalog-aws\",\n\t\t\"servicecatalog-azure\",\n\t\t\"hpa\",\n\t\t\"pdb\",\n\t\t\"secret\",\n\t}\n\n\t// Pull down kube configs from Vault.\n\tif err := kubeObjects.getKubeConfigs(cfg); err != nil {\n\t\treturn kubeObjects, err\n\t}\n\n\t// Decode Kubernetes Objects from files.\n\tif err := kubeObjects.processObjects(cfg, possibleFiles); err != nil {\n\t\treturn kubeObjects, err\n\t}\n\n\t// Perform checks/namespacing to ensure resources will not conflict with those of other services.\n\tif validationErr := kubeObjects.validateAndTag(); validationErr != nil {\n\t\treturn kubeObjects, validationErr\n\t}\n\n\tdeploymentErr := prepareDeployment(kubeObjects.parentObject(), cfg.SHA)\n\treturn kubeObjects, deploymentErr\n}", "func GetConfigServerEndpoint() (string, error) {\n\tconfigServerURL := config.GetConfigServerConf().ServerURI\n\tif configServerURL == \"\" {\n\t\tif registry.DefaultServiceDiscoveryService != nil {\n\t\t\topenlog.Debug(\"find config server in registry\")\n\t\t\tccURL, err := endpoint.GetEndpoint(\"default\", \"CseConfigCenter\", \"latest\")\n\t\t\tif err != nil {\n\t\t\t\topenlog.Warn(\"failed to find config server endpoints, err: \" + err.Error())\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t\tconfigServerURL = ccURL\n\t\t} else {\n\t\t\treturn \"\", ErrRegistryDisabled\n\t\t}\n\t}\n\n\treturn configServerURL, nil\n}", "func NewEKSService(service eks.Service) cluster.Service {\n\treturn eksService{\n\t\tservice: service,\n\t}\n}", "func (c *ClientMgr) Ecs() *ecs.Client {\n\tc.Lock()\n\tdefer c.Unlock()\n\ttokenUpdated, err := c.refreshToken()\n\tlogrus.Debugf(\"Token update: %v, %v\", tokenUpdated, err)\n\tif err != nil {\n\t\tlogrus.Errorf(\"Error refresh OpenAPI token: %v\", err)\n\t}\n\treturn c.ecs\n}", "func GetAWSCredentialConfig(config *cred.Config) (*aws.Config, error) {\n\tawsCredentials := credentials.NewStaticCredentials(config.Key, config.Secret, \"\")\n\t_, err := awsCredentials.Get()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get aws credential: %v, %v\", config.Key, err)\n\t}\n\tawsConfig := aws.NewConfig().WithRegion(config.Region).WithCredentials(awsCredentials)\n\treturn awsConfig, nil\n}", "func getK8sConfig(context string) clientcmd.ClientConfig {\n\trules := clientcmd.NewDefaultClientConfigLoadingRules()\n\toverrides := &clientcmd.ConfigOverrides{}\n\tif context != \"\" {\n\t\toverrides.CurrentContext = context\n\t}\n\treturn clientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, overrides)\n}", "func (c *RuntimeSecurityClient) GetConfig() (*api.SecurityConfigMessage, error) {\n\tresponse, err := c.apiClient.GetConfig(context.Background(), &api.GetConfigParams{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn response, nil\n}", "func GetClusterConfig(req *restful.Request, resp *restful.Response) {\n\tconst (\n\t\thandler = \"GetClusterConfig\"\n\t)\n\tspan := v1http.SetHTTPSpanContextInfo(req, handler)\n\tdefer span.Finish()\n\n\tr, err := generateData(req, getCls)\n\tif err != nil {\n\t\tutils.SetSpanLogTagError(span, err)\n\t\tblog.Errorf(\"%s | err: %v\", common.BcsErrStorageGetResourceFailStr, err)\n\t\tlib.ReturnRest(&lib.RestResponse{\n\t\t\tResp: resp,\n\t\t\tErrCode: common.BcsErrStorageGetResourceFail,\n\t\t\tMessage: common.BcsErrStorageGetResourceFailStr})\n\t\treturn\n\t}\n\tlib.ReturnRest(&lib.RestResponse{Resp: resp, Data: r})\n}", "func configForContext(context string) (*rest.Config, error) {\n\tconfig, err := kube.GetConfig(context).ClientConfig()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not get Kubernetes config for context %q: %s\", context, err)\n\t}\n\treturn config, nil\n}", "func (edge EdgeClusterServiceDetail) GetKubeConfig() *rest.Config {\n\tvar kubeconfig string\n\n\t//get hoem directory path\n\thomeDir := microbusiness.GetHomeDirectoryPath()\n\tlog.Print(homeDir)\n\n\tif homeDir != \"\" {\n\t\tflag.StringVar(&kubeconfig, \"kubeconfig\", filepath.Join(homeDir, \".kube\", edge.ConfigName), \"(optional) path to config file\")\n\t} else {\n\t\tflag.StringVar(&kubeconfig, \"kubeconfig\", \"\", \"path to kube config file\")\n\t}\n\n\tlog.Println(\"building config ...\")\n\n\tconfigContext, err := clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\n\tmicrobusiness.HandleError(err)\n\n\treturn configContext\n}", "func (app *Application) GetCloudConfig(context *gin.Context) {\n\tclientIP := context.ClientIP()\n\n\tlog.Printf(\"Received cloud-config request from %s\", clientIP)\n\n\tvar server *compute.Server\n\n\tif clientIP != \"127.0.0.1\" {\n\t\tremoteMACAddress := arp.Search(clientIP)\n\t\tif remoteMACAddress == \"\" {\n\t\t\tcontext.String(http.StatusBadRequest,\n\t\t\t\t\"Sorry, I can't figure out your MAC address from your IPv4 address (%s).\", clientIP,\n\t\t\t)\n\n\t\t\treturn\n\t\t}\n\n\t\tserver = app.FindServerByMACAddress(remoteMACAddress)\n\t\tif server == nil {\n\t\t\tcontext.String(http.StatusBadRequest,\n\t\t\t\t\"Sorry, %s, I can't find the server your MAC address corresponds to.\",\n\t\t\t\tremoteMACAddress,\n\t\t\t)\n\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tlog.Printf(\"Request originates from local machine; treating this as a test request.\")\n\n\t\tserver = createTestServer()\n\t}\n\n\tcloudConfig, err := app.GenerateCloudConfig(*server)\n\tif err != nil {\n\t\tcontext.Error(err)\n\n\t\treturn\n\t}\n\n\tcloudConfigYaml, err := yaml.Marshal(cloudConfig)\n\tif err != nil {\n\n\t\tcontext.Error(err)\n\n\t\treturn\n\n\t}\n\n\tcontext.String(http.StatusOK, fmt.Sprintf(\"#cloud-config\\n%s\",\n\t\tstring(cloudConfigYaml),\n\t))\n}", "func (s *Service) getConfig(c echo.Context) error {\n\t// Get the config\n\tconf, err := s.datastore.GetConfig(c.Param(\"config_id\"))\n\tif err != nil {\n\t\t// Not found\n\t\tif errors.Is(err, shipyard.ErrNotFound) {\n\t\t\treturn echo.NewHTTPError(http.StatusNotFound, \"Requested resource was not found\")\n\t\t}\n\n\t\t// Other errors\n\t\ts.logger.Errorf(\"echo/getConfig get config: %s\")\n\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to get Config\")\n\t}\n\n\treturn c.JSON(http.StatusOK, conf)\n}", "func (c *AKSCluster) GetK8sConfig() ([]byte, error) {\n\tif c.k8sConfig != nil {\n\t\treturn c.k8sConfig, nil\n\t}\n\tclient, err := c.GetAKSClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient.With(log.Logger)\n\n\tdatabase := model.GetDB()\n\tdatabase.Where(model.AzureClusterModel{ClusterModelId: c.modelCluster.ID}).First(&c.modelCluster.Azure)\n\t//TODO check banzairesponses\n\tconfig, err := azureClient.GetClusterConfig(client, c.modelCluster.Name, c.modelCluster.Azure.ResourceGroup, \"clusterUser\")\n\tif err != nil {\n\t\t// TODO status code !?\n\t\treturn nil, err\n\t}\n\tlog.Info(\"Get k8s config succeeded\")\n\tc.k8sConfig = []byte(config.Properties.KubeConfig)\n\treturn c.k8sConfig, nil\n}", "func readConfig(c *cli.Context) (service.Config, error) {\n\typath := c.GlobalString(\"config\")\n\tconfig := service.Config{}\n\tif _, err := os.Stat(ypath); err != nil {\n\t\treturn config, errors.New(\"config file path is not valid\")\n\t}\n\tydata, err := ioutil.ReadFile(ypath)\n\tif err != nil {\n\t\treturn config, err\n\t}\n\terr = yaml.Unmarshal([]byte(ydata), &config)\n\treturn config, err\n}", "func GetConfig(c echo.Context) error {\n\tid := os.Getenv(\"SYSTEM_ID\")\n\tif len(id) == 0 {\n\t\treturn c.String(http.StatusInternalServerError, \"SYSTEM_ID is not set\")\n\t}\n\n\tsplit := strings.Split(id, \"-\")\n\tif len(split) != 3 {\n\t\treturn c.String(http.StatusInternalServerError, fmt.Sprintf(\"invalid SYSTEM_ID %q\", id))\n\t}\n\n\tconfig, err := schedule.GetConfig(c.Request().Context(), split[0]+\"-\"+split[1])\n\tif err != nil {\n\t\treturn c.String(http.StatusInternalServerError, err.Error())\n\t}\n\n\tlastRequest = time.Now()\n\treturn c.JSON(http.StatusOK, config)\n}", "func (p providerServices) EKSCtl() eksctl.EKSCtl {\n\treturn p.eksctl\n}", "func GetEndpointConfig(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *EndpointConfigState, opts ...pulumi.ResourceOption) (*EndpointConfig, error) {\n\tvar resource EndpointConfig\n\terr := ctx.ReadResource(\"aws-native:sagemaker:EndpointConfig\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (o Ocs) GetConfig(w http.ResponseWriter, r *http.Request) {\n\tmustNotFail(render.Render(w, r, response.DataRender(&data.ConfigData{\n\t\tVersion: \"1.7\", // TODO get from env\n\t\tWebsite: \"ocis\", // TODO get from env\n\t\tHost: \"\", // TODO get from FRONTEND config\n\t\tContact: \"\", // TODO get from env\n\t\tSSL: \"true\", // TODO get from env\n\t})))\n}", "func (c *KubernetesSpecification) GetConfigForEndpoint(masterURL string, token interfaces.TokenRecord) (*restclient.Config, error) {\n\treturn clientcmd.BuildConfigFromKubeconfigGetter(masterURL, func() (*clientcmdapi.Config, error) {\n\n\t\tname := \"cluster-0\"\n\n\t\t// Create a config\n\n\t\t// Initialize a new config\n\t\tcontext := clientcmdapi.NewContext()\n\t\tcontext.Cluster = name\n\t\tcontext.AuthInfo = name\n\n\t\t// Configure the cluster\n\t\tcluster := clientcmdapi.NewCluster()\n\t\tcluster.Server = masterURL\n\t\tcluster.InsecureSkipTLSVerify = true\n\n\t\t// Configure auth information\n\t\tauthInfo := clientcmdapi.NewAuthInfo()\n\t\terr := c.addAuthInfoForEndpoint(authInfo, token)\n\n\t\tconfig := clientcmdapi.NewConfig()\n\t\tconfig.Clusters[name] = cluster\n\t\tconfig.Contexts[name] = context\n\t\tconfig.AuthInfos[name] = authInfo\n\t\tconfig.CurrentContext = context.Cluster\n\n\t\treturn config, err\n\t})\n\n}", "func (b *backend) getClientConfig(s logical.Storage, region, stsRole, clientType string) (*aws.Config, error) {\n\n\tconfig, err := b.getRawClientConfig(s, region, clientType)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif config == nil {\n\t\treturn nil, fmt.Errorf(\"could not compile valid credentials through the default provider chain\")\n\t}\n\n\tif stsRole != \"\" {\n\t\tassumeRoleConfig, err := b.getRawClientConfig(s, region, \"sts\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif assumeRoleConfig == nil {\n\t\t\treturn nil, fmt.Errorf(\"could not configure STS client\")\n\t\t}\n\t\tassumedCredentials := stscreds.NewCredentials(session.New(assumeRoleConfig), stsRole)\n\t\t// Test that we actually have permissions to assume the role\n\t\tif _, err = assumedCredentials.Get(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tconfig.Credentials = assumedCredentials\n\t}\n\n\treturn config, nil\n}", "func (client *Client) DescribeClusterServiceConfigForAdmin(request *DescribeClusterServiceConfigForAdminRequest) (response *DescribeClusterServiceConfigForAdminResponse, err error) {\n\tresponse = CreateDescribeClusterServiceConfigForAdminResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func (service *envConfigurationService) GetEdgeClusterServiceAddress() (string, error) {\n\taddress := os.Getenv(\"EDGE_CLUSTER_ADDRESS\")\n\tif strings.Trim(address, \" \") == \"\" {\n\t\treturn \"\", commonErrors.NewUnknownError(\"EDGE_CLUSTER_ADDRESS is required\")\n\t}\n\n\treturn address, nil\n}", "func GetE2EConfig(mode ops.Mode, cmd *cobra.Command) (*ops.E2EConfig, error) {\n\tflags := cmd.PersistentFlags()\n\tcfg := mode.Get().E2EConfig\n\tif flags.Changed(e2eFocusFlag) {\n\t\tfocus, err := flags.GetString(e2eFocusFlag)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"couldn't retrieve focus flag\")\n\t\t}\n\t\tcfg.Focus = focus\n\t}\n\n\tif flags.Changed(e2eSkipFlag) {\n\t\tskip, err := flags.GetString(e2eSkipFlag)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"couldn't retrieve skip flag\")\n\t\t}\n\t\tcfg.Skip = skip\n\t}\n\treturn &cfg, nil\n}", "func (a *Client) GetConfig(params *GetConfigParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetConfigOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetConfigParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"getConfig\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/api/v1/customers/{cUUID}/runtime_config/{scope}\",\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: &GetConfigReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\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.(*GetConfigOK)\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 getConfig: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func getConfig(cfgFile string, pCfg *ContivConfig) error {\n\tbytes, err := ioutil.ReadFile(cfgFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpCfg.SvcSubnet = defSvcSubnet\n\terr = json.Unmarshal(bytes, pCfg)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error parsing config file: %s\", err)\n\t}\n\n\treturn nil\n}", "func GetK8sConfig(c *gin.Context) ([]byte, bool) {\n\tlog := logger.WithFields(logrus.Fields{\"tag\": \"GetKubernetesConfig\"})\n\tcommonCluster, ok := GetCommonClusterFromRequest(c)\n\tif ok != true {\n\t\treturn nil, false\n\t}\n\tkubeConfig, err := commonCluster.GetK8sConfig()\n\tif err != nil {\n\t\tlog.Errorf(\"Error getting config: %s\", err.Error())\n\t\tc.JSON(http.StatusBadRequest, htype.ErrorResponse{\n\t\t\tCode: http.StatusBadRequest,\n\t\t\tMessage: \"Error getting kubeconfig\",\n\t\t\tError: err.Error(),\n\t\t})\n\t\treturn nil, false\n\t}\n\treturn kubeConfig, true\n}", "func (p *Provider) GetConfigFile() (*kubernetes.Clientset, string, error) {\n\tsDec, err := base64.StdEncoding.DecodeString(p.Config)\n\tif err != nil {\n\t\treturn nil, \"\", fmt.Errorf(\"Error decoding k8 config: %s\", err)\n\t}\n\tconfigFile, err := ioutil.TempFile(\"\", \"k8-config\")\n\tif err != nil {\n\t\treturn nil, \"\", fmt.Errorf(\"Error creating tmp file: %s\", err)\n\t}\n\terr = ioutil.WriteFile(configFile.Name(), sDec, 0400)\n\tif err != nil {\n\t\treturn nil, configFile.Name(), fmt.Errorf(\"Error writing to tmp file: %s\", err)\n\t}\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", configFile.Name())\n\tif err != nil {\n\t\treturn nil, configFile.Name(), fmt.Errorf(\"Error reading k8 config: %s\", err)\n\t}\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, configFile.Name(), fmt.Errorf(\"Error creating k8 client: %s\", err)\n\t}\n\treturn clientset, configFile.Name(), nil\n}", "func (client *Client) DescribeClusterServiceConfigTag(request *DescribeClusterServiceConfigTagRequest) (response *DescribeClusterServiceConfigTagResponse, err error) {\n\tresponse = CreateDescribeClusterServiceConfigTagResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func GetConfig(configFileName string, trafficOpsHost string, trafficServerHost string, params []TrafficOpsParameter) (string, error) {\n\tswitch configFileName {\n\tcase \"storage.config\":\n\t\treturn createStorageDotConfig(trafficOpsHost, trafficServerHost, params)\n\tdefault:\n\t\treturn \"\", errors.New(\"Config file '%s' not valid\")\n\t}\n}", "func (o ClusterOutput) IdentityServiceConfig() ClusterIdentityServiceConfigOutput {\n\treturn o.ApplyT(func(v *Cluster) ClusterIdentityServiceConfigOutput { return v.IdentityServiceConfig }).(ClusterIdentityServiceConfigOutput)\n}", "func (c ServiceConfig) GetHost() string {\n\treturn c.Host\n}", "func (c ServiceConfig) GetHost() string {\n\treturn c.Host\n}", "func GetGceConfig(project, cluster, clusterLocation, zone, node string) (*GceConfig, error) {\n\tif project != \"\" {\n\t\tglog.Infof(\"Using metadata all from flags\")\n\t\tif cluster == \"\" {\n\t\t\tglog.Warning(\"Cluster name was not set. This can be set with --cluster-name\")\n\t\t}\n\t\tif clusterLocation == \"\" {\n\t\t\tglog.Warning(\"Cluster location was not set. This can be set with --cluster-location\")\n\t\t}\n\t\tif zone == \"\" {\n\t\t\t// zone is only used by the older gke_container\n\t\t\tglog.Info(\"Zone was not set. This can be set with --zone-override\")\n\t\t}\n\t\tif node == \"\" {\n\t\t\tglog.Warning(\"Node was not set. This can be set with --node-name\")\n\t\t}\n\t\treturn &GceConfig{\n\t\t\tProject: project,\n\t\t\tZone: zone,\n\t\t\tCluster: cluster,\n\t\t\tClusterLocation: clusterLocation,\n\t\t\tInstance: node,\n\t\t}, nil\n\t}\n\n\tif !gce.OnGCE() {\n\t\treturn nil, fmt.Errorf(\"Not running on GCE.\")\n\t}\n\n\tvar err error\n\tif project == \"\" {\n\t\tproject, err = gce.ProjectID()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error while getting project id: %v\", err)\n\t\t}\n\t}\n\n\tif cluster == \"\" {\n\t\tcluster, err = gce.InstanceAttributeValue(\"cluster-name\")\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error while getting cluster name: %v\", err)\n\t\t}\n\t\tcluster = strings.TrimSpace(cluster)\n\t\tif cluster == \"\" {\n\t\t\treturn nil, fmt.Errorf(\"cluster-name metadata was empty\")\n\t\t}\n\t}\n\n\t// instance/name endpoint is not available on the GKE metadata server.\n\t// Try GCE instance/name endpoint. If error, try instance/hostname.\n\t// If instance/hostname, remove domain to replicate instance/name.\n\tif node == \"\" {\n\t\tnode, err = gce.InstanceName()\n\t\tif err != nil {\n\t\t\tnode, err = gce.Hostname()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error while getting instance (node) name: %v\", err)\n\t\t\t}\n\t\t\tnode = strings.Split(node, \".\")[0]\n\t\t\tglog.Warningf(\"using %s as instance/name\", node)\n\t\t}\n\t}\n\n\tinstanceId, err := gce.InstanceID()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error while getting instance id: %v\", err)\n\t}\n\n\tif zone == \"\" {\n\t\tzone, err = gce.Zone()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error while getting zone: %v\", err)\n\t\t}\n\t}\n\n\tif clusterLocation == \"\" {\n\t\tclusterLocation, err = gce.InstanceAttributeValue(\"cluster-location\")\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error while getting cluster location: %v\", err)\n\t\t}\n\t\tclusterLocation = strings.TrimSpace(clusterLocation)\n\t\tif clusterLocation == \"\" {\n\t\t\treturn nil, fmt.Errorf(\"cluster-location metadata was empty\")\n\t\t}\n\t}\n\n\treturn &GceConfig{\n\t\tProject: project,\n\t\tZone: zone,\n\t\tCluster: cluster,\n\t\tClusterLocation: clusterLocation,\n\t\tInstance: node,\n\t\tInstanceId: instanceId,\n\t}, nil\n}", "func getConfig(serverURL, kubeconfig string) (*rest.Config, error) {\n\tif kubeconfig == \"\" {\n\t\tkubeconfig = os.Getenv(\"KUBECONFIG\")\n\t}\n\t// If we have an explicit indication of where the kubernetes config lives, read that.\n\tif kubeconfig != \"\" {\n\t\treturn clientcmd.BuildConfigFromFlags(serverURL, kubeconfig)\n\t}\n\t// If not, try the in-cluster config.\n\tif c, err := rest.InClusterConfig(); err == nil {\n\t\treturn c, nil\n\t}\n\t// If no in-cluster config, try the default location in the user's home directory.\n\tif usr, err := user.Current(); err == nil {\n\t\tif c, err := clientcmd.BuildConfigFromFlags(\"\", filepath.Join(usr.HomeDir, \".kube\", \"config\")); err == nil {\n\t\t\treturn c, nil\n\t\t}\n\t}\n\n\treturn nil, fmt.Errorf(\"could not create a valid kubeconfig\")\n}", "func parseEksConfig(stack interfaces.IStack) (*EksConfig, error) {\n\ttemplatedVars, err := stack.GetTemplatedVars(nil, map[string]interface{}{})\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\tprovisionerValues, ok := templatedVars[ProvisionerKey].(map[interface{}]interface{})\n\tif !ok {\n\t\treturn nil, errors.New(\"No provisioner found in stack config. You must at least set the binary path.\")\n\t}\n\tlog.Logger.Tracef(\"Marshalling: %#v\", provisionerValues)\n\n\t// marshal then unmarshal the provisioner values to get the command parameters\n\tbyteData, err := yaml.Marshal(provisionerValues)\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\n\tlog.Logger.Tracef(\"Marshalled to: %s\", string(byteData[:]))\n\n\tvar eksConfig EksConfig\n\terr = yaml.Unmarshal(byteData, &eksConfig)\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\n\tif eksConfig.Binary == \"\" {\n\t\teksConfig.Binary = eksDefaultBinary\n\t\tlog.Logger.Warnf(\"Using default %s binary '%s'. It's safer to explicitly set the path to a versioned \"+\n\t\t\t\"binary (e.g. %s-1.2.3) in the provisioner configuration\", eksProvisionerName, eksDefaultBinary,\n\t\t\teksDefaultBinary)\n\t}\n\n\teksConfig.clusterName = eksConfig.Params.GetCluster[configKeyEKSClusterName]\n\n\treturn &eksConfig, nil\n}", "func NewConfigService(useLocalFileSystem bool, project string, stage string, service string, resourceHandler *api.ResourceHandler) ConfigService {\n\treturn &configServiceImpl{\n\t\tuseLocalFileSystem: useLocalFileSystem,\n\t\tproject: project,\n\t\tstage: stage,\n\t\tservice: service,\n\t\tresourceHandler: resourceHandler,\n\t}\n}", "func (e *endpoints) getTLSConfig(ctx context.Context) func(*tls.ClientHelloInfo) (*tls.Config, error) {\n\treturn func(hello *tls.ClientHelloInfo) (*tls.Config, error) {\n\t\tcerts, roots, err := e.getCerts(ctx)\n\t\tif err != nil {\n\t\t\te.c.Log.Errorf(\"Could not generate TLS config for gRPC client %v: %v\", hello.Conn.RemoteAddr(), err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\tc := &tls.Config{\n\t\t\t// When bootstrapping, the agent does not yet have\n\t\t\t// an SVID. In order to include the bootstrap endpoint\n\t\t\t// in the same server as the rest of the Node API,\n\t\t\t// request but don't require a client certificate\n\t\t\tClientAuth: tls.VerifyClientCertIfGiven,\n\n\t\t\tCertificates: certs,\n\t\t\tClientCAs: roots,\n\t\t}\n\t\treturn c, nil\n\t}\n}", "func GetEciScalingConfiguration(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *EciScalingConfigurationState, opts ...pulumi.ResourceOption) (*EciScalingConfiguration, error) {\n\tvar resource EciScalingConfiguration\n\terr := ctx.ReadResource(\"alicloud:ess/eciScalingConfiguration:EciScalingConfiguration\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func configForContext(kubeConfig, kubeContext string) (*rest.Config, error) {\n\tconfig, err := kube.GetConfig(kubeContext, kubeConfig).ClientConfig()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not get Kubernetes config for context %q: %s\", kubeContext, err)\n\t}\n\treturn config, nil\n}", "func GetConfig(c *caddy.Controller) *Config {\r\n\tctx := c.Context().(*netContext)\r\n\tkey := strings.Join(c.ServerBlockKeys, \"~\")\r\n\r\n\t//only check for config if the value is proxy or echo\r\n\t//we need to do this because we specify the ports in the server block\r\n\t//and those values need to be ignored as they are also sent from caddy main process.\r\n\tif strings.Contains(key, \"echo\") || strings.Contains(key, \"proxy\") {\r\n\t\tif cfg, ok := ctx.keysToConfigs[key]; ok {\r\n\t\t\treturn cfg\r\n\t\t}\r\n\t}\r\n\r\n\t// we should only get here if value of key in server block\r\n\t// is not echo or proxy i.e port number :12017\r\n\t// we can't return a nil because caddytls.RegisterConfigGetter will panic\r\n\t// so we return a default (blank) config value\r\n\tcaddytlsConfig, err := caddytls.NewConfig(ctx.instance)\r\n\tif err != nil {\r\n\t\tlog.Printf(\"[ERROR] Making new TLS configuration: %v\", err)\r\n\t\treturn new(Config)\r\n\t}\r\n\r\n\treturn &Config{TLS: caddytlsConfig}\r\n}", "func GetSDKConfig() string {\n\treturn myViper.GetString(\"client.sdkconfig\")\n}", "func GetConfig() common.AresServerConfig {\n\treturn config\n}", "func loadConfig(configFile string) service.ServiceConfig {\n conf := service.ServiceConfig{}\n\n if err := loader.FromFile(&conf, configFile); err != nil {\n StdErr.Write([]byte(err.Error()))\n os.Exit(ERR_CONFIG)\n }\n\n return conf\n}", "func AWSServiceEndpoint() *AWSServiceEndpointApplyConfiguration {\n\treturn &AWSServiceEndpointApplyConfiguration{}\n}", "func GetConfig(appOpts servertypes.AppOptions) *Config {\n\treturn &Config{\n\t\tContractQueryGasLimit: cast.ToUint64(appOpts.Get(\"wasm.contract-query-gas-limit\")),\n\t\tContractDebugMode: cast.ToBool(appOpts.Get(\"wasm.contract-debug-mode\")),\n\t\tWriteVMMemoryCacheSize: cast.ToUint32(appOpts.Get(\"wasm.write-vm-memory-cache-size\")),\n\t\tReadVMMemoryCacheSize: cast.ToUint32(appOpts.Get(\"wasm.read-vm-memory-cache-size\")),\n\t\tNumReadVMs: cast.ToUint32(appOpts.Get(\"wasm.num-read-vms\")),\n\t}\n}", "func (c *Provider) EndpointConfig() fab.EndpointConfig {\n\treturn c.endpointConfig\n}", "func (cp configFactory) getConfig(app *model.App, vmConfig vm.Config, remoteConfig *remote.Config, forceOpts forceOptions,\n\toverrideCP func(env string) (kubeClient, error)) (*config, error) {\n\tscp := &stdClientProvider{\n\t\tapp: app,\n\t\tconfig: remoteConfig,\n\t\tverbosity: cp.verbosity,\n\t\tforceContext: forceOpts.k8sContext,\n\t\toverrideClientProvider: overrideCP,\n\t}\n\treturn cp.internalConfig(app, vmConfig, scp.Client, scp.Attrs)\n}", "func (pr *PeeringRequest) GetConfig(clientset kubernetes.Interface) (*rest.Config, error) {\n\treturn getConfig(clientset, pr.Spec.KubeConfigRef)\n}", "func (z *ZkClient) InitServiceConfig(path string, config map[string]string) {\n\n}", "func getClusterConfig() (rest.Config, error) {\n\tkubeconfig, exists := os.LookupEnv(\"KUBECONFIG\")\n\tif exists != true {\n\t\tlogrus.Warnf(\"KUBECONFIG env var not set\")\n\t}\n\tlogrus.WithField(\"KUBECONFIG\", kubeconfig).Debug(\"Using kubeconfig from env:\")\n\n\t// use the current context in kubeconfig\n\tlogrus.Debug(\"Using the provided KUBECONFIG for the Out-of-cluster config\")\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\tif err != nil {\n\t\treturn rest.Config{}, err\n\t}\n\n\treturn *config, nil\n}", "func (m *MockProviderKubectlClient) GetEksaAWSDatacenterConfig(arg0 context.Context, arg1, arg2, arg3 string) (*v1alpha1.AWSDatacenterConfig, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetEksaAWSDatacenterConfig\", arg0, arg1, arg2, arg3)\n\tret0, _ := ret[0].(*v1alpha1.AWSDatacenterConfig)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (sc SfcConfig) getConfig() (*types.SfcConfig, error) {\n\t// get the SFC configuration only once\n\tcfg, err, _ := sc.cg.Do(\"cfg\", func() (interface{}, error) {\n\t\treturn repository.R().SfcConfiguration()\n\t})\n\n\t// loader failed\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn cfg.(*types.SfcConfig), nil\n}", "func (c *ConfigService) Get() (*Config, *http.Response, error) {\n\tconfig := new(Config)\n\tapiError := new(APIError)\n\tresp, err := c.sling.New().Get(\"configuration.json\").Receive(config, apiError)\n\treturn config, resp, relevantError(err, *apiError)\n}", "func (c baseClient) getEngineConfigFilePath(ctx context.Context, engine containerd.Container) (string, error) {\n\tspec, err := engine.Spec(ctx)\n\tconfigFile := \"\"\n\tif err != nil {\n\t\treturn configFile, err\n\t}\n\tfor i := 0; i < len(spec.Process.Args); i++ {\n\t\targ := spec.Process.Args[i]\n\t\tif strings.HasPrefix(arg, \"--config-file\") {\n\t\t\tif strings.Contains(arg, \"=\") {\n\t\t\t\tsplit := strings.SplitN(arg, \"=\", 2)\n\t\t\t\tconfigFile = split[1]\n\t\t\t} else {\n\t\t\t\tif i+1 >= len(spec.Process.Args) {\n\t\t\t\t\treturn configFile, ErrMalformedConfigFileParam\n\t\t\t\t}\n\t\t\t\tconfigFile = spec.Process.Args[i+1]\n\t\t\t}\n\t\t}\n\t}\n\n\tif configFile == \"\" {\n\t\t// TODO - any more diagnostics to offer?\n\t\treturn configFile, ErrEngineConfigLookupFailure\n\t}\n\treturn configFile, nil\n}", "func (c baseClient) getEngineConfigFilePath(ctx context.Context, engine containerd.Container) (string, error) {\n\tspec, err := engine.Spec(ctx)\n\tconfigFile := \"\"\n\tif err != nil {\n\t\treturn configFile, err\n\t}\n\tfor i := 0; i < len(spec.Process.Args); i++ {\n\t\targ := spec.Process.Args[i]\n\t\tif strings.HasPrefix(arg, \"--config-file\") {\n\t\t\tif strings.Contains(arg, \"=\") {\n\t\t\t\tsplit := strings.SplitN(arg, \"=\", 2)\n\t\t\t\tconfigFile = split[1]\n\t\t\t} else {\n\t\t\t\tif i+1 >= len(spec.Process.Args) {\n\t\t\t\t\treturn configFile, ErrMalformedConfigFileParam\n\t\t\t\t}\n\t\t\t\tconfigFile = spec.Process.Args[i+1]\n\t\t\t}\n\t\t}\n\t}\n\n\tif configFile == \"\" {\n\t\t// TODO - any more diagnostics to offer?\n\t\treturn configFile, ErrEngineConfigLookupFailure\n\t}\n\treturn configFile, nil\n}", "func (c *ConfigServer) GetConfig(ctx context.Context, req *empty.Empty) (*api.GetConfigResponse, error) {\n\tclient := getClient(ctx)\n\tallowed, err := auth.IsAuthorized(client, \"\", \"list\", \"\", \"namespaces\", \"\")\n\tif err != nil || !allowed {\n\t\treturn nil, err\n\t}\n\n\tsysConfig, err := client.GetSystemConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnodePool := &api.NodePool{\n\t\tLabel: *sysConfig.GetValue(\"applicationNodePoolLabel\"),\n\t\tOptions: make([]*api.NodePoolOption, 0),\n\t}\n\n\tnodePoolOptions, err := sysConfig.NodePoolOptions()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttype ConfigServer struct{}\n\tfor _, option := range nodePoolOptions {\n\t\tnodePool.Options = append(nodePool.Options, &api.NodePoolOption{\n\t\t\tName: option.Name,\n\t\t\tValue: option.Value,\n\t\t})\n\t}\n\n\treturn &api.GetConfigResponse{\n\t\tApiUrl: sysConfig[\"ONEPANEL_API_URL\"],\n\t\tDomain: sysConfig[\"ONEPANEL_DOMAIN\"],\n\t\tFqdn: sysConfig[\"ONEPANEL_FQDN\"],\n\t\tNodePool: nodePool,\n\t}, err\n}", "func (r *ECMResource) Get(id string) (*ECMConfig, error) {\n\tvar item ECMConfig\n\tif err := r.c.ReadQuery(BasePath+ECMEndpoint, &item); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &item, nil\n}", "func GetConfig() interface{} {\n\treturn std.GetConfig()\n}", "func (c *Config) GetService(host string) *Service {\n\tdomainPattern := regexp.MustCompile(`(\\w*\\:\\/\\/)?(.+)` + c.Domain)\n\tparts := domainPattern.FindAllString(host, -1)\n\t//we must lock the access as the configuration can be dynamically loaded\n\tselect {\n\tcase srv := <-configChan:\n\t\tc.Services = srv\n\tdefault:\n\t}\n\tfor _, s := range c.Services {\n\t\tif len(parts) > 0 && s.Name+c.Domain == parts[0] {\n\t\t\treturn &s\n\t\t}\n\t}\n\n\treturn nil\n}", "func GetConfig(host string, verifyTLS bool, apiKey string, project string, config string) (models.ConfigInfo, Error) {\n\tvar params []queryParam\n\tparams = append(params, queryParam{Key: \"project\", Value: project})\n\tparams = append(params, queryParam{Key: \"config\", Value: config})\n\n\turl, err := generateURL(host, \"/v3/configs/config\", params)\n\tif err != nil {\n\t\treturn models.ConfigInfo{}, Error{Err: err, Message: \"Unable to generate url\"}\n\t}\n\n\tstatusCode, _, response, err := GetRequest(url, verifyTLS, apiKeyHeader(apiKey))\n\tif err != nil {\n\t\treturn models.ConfigInfo{}, Error{Err: err, Message: \"Unable to fetch configs\", Code: statusCode}\n\t}\n\n\tvar result map[string]interface{}\n\terr = json.Unmarshal(response, &result)\n\tif err != nil {\n\t\treturn models.ConfigInfo{}, Error{Err: err, Message: \"Unable to parse API response\", Code: statusCode}\n\t}\n\n\tconfigInfo, ok := result[\"config\"].(map[string]interface{})\n\tif !ok {\n\t\treturn models.ConfigInfo{}, Error{Err: fmt.Errorf(\"Unexpected type parsing config, expected map[string]interface{}, got %T\", result[\"config\"]), Message: \"Unable to parse API response\", Code: statusCode}\n\t}\n\tinfo := models.ParseConfigInfo(configInfo)\n\treturn info, Error{}\n}", "func determineConfig() (*rest.Config, error) {\n\tkubeconfigPath := os.Getenv(\"KUBECONFIG\")\n\tvar config *rest.Config\n\tvar err error\n\n\t// determine whether to use in cluster config or out of cluster config\n\t// if kubeconfigPath is not specified, default to in cluster config\n\t// otherwise, use out of cluster config\n\tif kubeconfigPath == \"\" {\n\t\tlog.Info(\"Using in cluster k8s config\")\n\t\tconfig, err = rest.InClusterConfig()\n\t} else {\n\t\tlog.Info(\"Using out of cluster k8s config: \", kubeconfigPath)\n\n\t\tconfig, err = clientcmd.BuildConfigFromFlags(\"\", kubeconfigPath)\n\t}\n\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"determine Kubernetes config failed\")\n\t}\n\n\treturn config, nil\n}", "func (r *AppConfig) GetDefaultServiceConfig() CommonServiceConfig {\n\treturn r.DefaultServiceConfig\n}", "func (c *Client) DatacenterConfigGet(datacenterName string) (*DatacenterConfig, error) {\n\tvar datacenterConfig DatacenterConfig\n\n\terr := c.rpcClient.CallFor(\n\t\t&datacenterConfig,\n\t\t\"datacenter_config\",\n\t\tdatacenterName)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &datacenterConfig, nil\n}" ]
[ "0.6821646", "0.67600626", "0.66528106", "0.6580003", "0.657921", "0.6567093", "0.624718", "0.61671364", "0.6118922", "0.60779226", "0.60774213", "0.60474586", "0.59474874", "0.59273213", "0.5882051", "0.5842291", "0.5829497", "0.5804335", "0.57492363", "0.5749054", "0.57445234", "0.5738926", "0.5737981", "0.5737009", "0.57130265", "0.56660265", "0.5664692", "0.5648582", "0.56080717", "0.5586027", "0.5570339", "0.556454", "0.55554855", "0.55517554", "0.55461454", "0.5503047", "0.5497285", "0.5486408", "0.54696506", "0.5468359", "0.5457105", "0.54566395", "0.5451721", "0.54320425", "0.54283357", "0.54213804", "0.5386329", "0.5374118", "0.5367889", "0.5362287", "0.53601754", "0.5358133", "0.5352991", "0.5347362", "0.5336133", "0.53340876", "0.5333206", "0.53298897", "0.5328312", "0.53224576", "0.531982", "0.5315417", "0.5306369", "0.5305382", "0.52936965", "0.52936274", "0.5288364", "0.52799046", "0.52799046", "0.52770627", "0.52765685", "0.5259211", "0.5258199", "0.5253932", "0.52492607", "0.52461195", "0.52442163", "0.5241172", "0.52324426", "0.5218398", "0.52136916", "0.5211932", "0.5210439", "0.5208906", "0.52062774", "0.5205921", "0.5203272", "0.5195031", "0.5189572", "0.51871586", "0.51847035", "0.51847035", "0.5181943", "0.5181325", "0.5180845", "0.517592", "0.51671565", "0.5164308", "0.5161854", "0.51559013" ]
0.83150405
0
GetPageConfig will parse the web post entry at filepath.
GetPageConfig будет парсить веб-пост в файле по пути filepath.
func GetPageConfig(filepath, sitepath string) (Post, error) { cfg, err := getPageConfig(filepath) if err != nil { return cfg, err } cfg.FilePath = filepath cfg.SitePath = sitepath if cfg.Date != "" { t, err := time.Parse(time.RFC3339, cfg.Date) if err != nil { return cfg, fmt.Errorf("parsing date %s: %w", cfg.Date, err) } date := t.Format(time.RFC3339) if cfg.Date != date { return cfg, fmt.Errorf("dates don't match: %s != %s", cfg.Date, date) } } return cfg, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func ParseConfigFile(url string, wd *url.URL) (*Config, error) {\n\treturn ParseConfigFileWithSchemes(urlfetch.DefaultSchemes, url, wd)\n}", "func (o Ocs) GetConfig(w http.ResponseWriter, r *http.Request) {\n\tmustNotFail(render.Render(w, r, response.DataRender(&data.ConfigData{\n\t\tVersion: \"1.7\", // TODO get from env\n\t\tWebsite: \"ocis\", // TODO get from env\n\t\tHost: \"\", // TODO get from FRONTEND config\n\t\tContact: \"\", // TODO get from env\n\t\tSSL: \"true\", // TODO get from env\n\t})))\n}", "func GetConfigHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tconfigName := ps.ByName(\"config\")\n\n\tconfiguration, err := ubus.UciGetConfig(uci.ConfigType(configName))\n\tif err != nil {\n\t\trend.JSON(w, http.StatusOK, map[string]string{\"error\": err.Error()})\n\t\treturn\n\t}\n\n\trend.JSON(w, http.StatusOK, configuration)\n}", "func GetConfig(path string) (*viper.Viper, error) {\n\tconfig, err := getConfig(path, \"WILLIAM\", \"yaml\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn config, nil\n}", "func GetConfigHandler(w http.ResponseWriter, r *http.Request) {\n\thttp.ServeFile(w, r, \"swagger.json\")\n}", "func GetConfig(filePath string) (*Configuration, error) {\n\tpath, _ := filepath.Abs(filePath)\n\tfile, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconfig := Configuration{}\n\tdecoder := json.NewDecoder(file)\n\terr = decoder.Decode(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconfig.processConfig()\n\n\treturn &config, nil\n}", "func GetConfig(filePath string) *Config {\n\tviper.SetConfigFile(filePath)\n\terr := viper.ReadInConfig()\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to Read Config: %v\\n\", err)\n\t}\n\tvar C Config\n\tviper.Unmarshal(&C)\n\tviper.SetDefault(`loglevel`, `info`)\n\tviper.SetDefault(`interval`, `5s`)\n\tC.LogLevel = viper.GetString(`loglevel`)\n\tC.Interval = viper.GetDuration(`interval`)\n\tfor _, c := range C.LBServers {\n\t\tif c.PoolWorkers < len(c.Metrics)*10 {\n\t\t\tc.PoolWorkers = len(c.Metrics) * 10\n\t\t}\n\t\tif c.PoolWorkerQueue < 1000 {\n\t\t\tc.PoolWorkerQueue = 1000\n\t\t}\n\t}\n\treturn &C\n}", "func GetConfig() string {\n\tproberMu.Lock()\n\tdefer proberMu.Unlock()\n\treturn prober.textConfig\n}", "func (CTRL *BaseController) ConfigPage(page string) {\n\tCTRL.GetDB()\n\tCTRL.GetCache()\n\ttheme := template.GetActiveTheme(false)\n\tCTRL.Layout = theme[0] + \"/\" + \"layout-admin.html\"\n\tdevice := CTRL.Ctx.Input.GetData(\"device_type\").(string)\n\tCTRL.LayoutSections = make(map[string]string)\n\tCTRL.LayoutSections[\"Head\"] = theme[0] + \"/\" + \"partial/html_head_\" + device + \".html\"\n\tCTRL.TplName = theme[0] + \"/\" + page\n\tCTRL.Data[\"Theme\"] = theme[0]\n\tCTRL.Data[\"Style\"] = theme[1]\n\tCTRL.Data[\"ModuleMenu\"] = CTRL.GetModuleMenu()\n\tCTRL.GetBlocks()\n\t//CTRL.GetActiveModule()\n\t//CTRL.GetActiveCategory()\n\t//CTRL.GetActiveAds()\n}", "func getConfig(path string) (*configparser.ConfigParser, error){\r\n p, err := configparser.NewConfigParserFromFile(path)\r\n if err != nil {\r\n return nil,err\r\n }\r\n\r\n return p,nil\r\n}", "func GetConfig(filePath string) (*Config, error) {\n\tconfig := Config{}\n\tfile, err := os.Open(filePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\tdecoder := json.NewDecoder(file)\n\terr = decoder.Decode(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &config, nil\n}", "func (c *GinHttp) getConfig() *GinHttp {\n\tif _, err := toml.DecodeFile(ConfPath+c.getTomlFile(), &c); err != nil {\n\t\tfmt.Println(err)\n\t\treturn c\n\t}\n\treturn c\n}", "func GetConfigFile() string {\n\treturn *configFile\n}", "func GetConfig(configFile string) (*viper.Viper, error) {\n\ts, err := os.Stat(configFile)\n\tif os.IsNotExist(err) {\n\t\treturn nil, err\n\t}\n\tif s.IsDir() {\n\t\treturn nil, errors.New(\"Config file is not a file\")\n\t}\n\tc := viper.New()\n\tdir := filepath.Dir(configFile)\n\tc.SetConfigName(strings.TrimSuffix(filepath.Base(configFile), filepath.Ext(configFile)))\n\tc.SetConfigType(\"json\")\n\tc.AddConfigPath(dir)\n\terr = c.ReadInConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn c, nil\n}", "func GetConfig(filePath string) (Config, error) {\n\traw, err := ioutil.ReadFile(filePath)\n\n\tvar config Config\n\terr = json.Unmarshal(raw, &config)\n\n\treturn config, err\n}", "func (c Config) GetConfigFile() string {\n\treturn c.viper.GetString(configFile)\n}", "func GetPageFile(c *gin.Context) {\n p, _ := c.Get(\"serviceProvider\")\n var serviceProvider *services.ServiceProvider\n serviceProvider = p.(*services.ServiceProvider)\n\tfileName := c.Param(\"page\")\n\thtmlFolder := serviceProvider.GetConfig().StaticFolder\n\tpath := fmt.Sprintf(\"%s/_next/static/chunks/pages/%s\", htmlFolder, fileName)\n\tc.File(path)\n}", "func (m *Tracing_Http) GetConfig() *_struct.Struct {\n\tif x, ok := m.GetConfigType().(*Tracing_Http_Config); ok {\n\t\treturn x.Config\n\t}\n\treturn nil\n}", "func GetConfig(f string) (*Configs, error) {\n\tconfig := &Configs{}\n\tfile, err := ioutil.ReadFile(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = GetYaml(file, config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn config, nil\n}", "func GetConfig(f string) (*Configs, error) {\n\tconfig := &Configs{}\n\tfile, err := os.ReadFile(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = GetYaml(file, config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn config, nil\n}", "func GetConfig() datatypes.Config {\n\tlogLevel := os.Getenv(\"LOG_LEVEL\")\n\tif logLevel != \"\" {\n\t\tlogging.SetLogLevel(logLevel)\n\t\tlogging.LogSystem(datatypes.Logging{Message: fmt.Sprintf(\"LOG_LEVEL set to %v from env var\", logLevel)})\n\t} else {\n\t\tlogging.LogSystem(datatypes.Logging{Message: \"LOG_LEVEL not found in ENV. Defaulting to ERROR\"})\n\t}\n\n\tlogging.LogInfo(datatypes.Logging{Message: \"** Reading in goDynaPerfSignature Config\"})\n\n\tserver := os.Getenv(\"DT_SERVER\")\n\tif server == \"\" {\n\t\tlogging.LogInfo(datatypes.Logging{Message: \"A Dynatrace server was not provided. Requests will not work unless a DT_SERVER is given in the POST body.\"})\n\t} else {\n\t\tlogging.LogInfo(datatypes.Logging{Message: fmt.Sprintf(\"Loaded default DT_SERVER: %v. This can be overridden with any API POST\", server)})\n\t}\n\n\tenv := os.Getenv(\"DT_ENV\")\n\tif env == \"\" {\n\t\tlogging.LogInfo(datatypes.Logging{Message: \"A Dynatrace environment was not provided. If your tenant has multiple environments, you will need to include the DT_ENV in the POST body of requests.\"})\n\t} else {\n\t\tlogging.LogInfo(datatypes.Logging{Message: fmt.Sprintf(\"Loaded default DT_ENV: %v. This can be overridden with any API POST.\", env)})\n\t}\n\n\tapiToken := os.Getenv(\"DT_API_TOKEN\")\n\tif apiToken == \"\" {\n\t\tlogging.LogInfo(datatypes.Logging{Message: \"A Dynatrace API token was not provided. DT_API_TOKEN must be given with every API POST.\"})\n\t} else {\n\t\tlogging.LogInfo(datatypes.Logging{Message: fmt.Sprintf(\"Loaded default DT_API_TOKEN: %v. This can be overridden with any API POST.\", apiToken)})\n\t}\n\n\tconfig := datatypes.Config{\n\t\tAPIToken: apiToken,\n\t\tEnv: env,\n\t\tServer: server,\n\t}\n\treturn config\n}", "func ParseConfig(configFile string) *SubmitConfig {\n\t// ------------------- load paddle config -------------------\n\tbuf, err := ioutil.ReadFile(configFile)\n\tconfig := SubmitConfig{}\n\tif err == nil {\n\t\tyamlErr := yaml.Unmarshal(buf, &config)\n\t\tif yamlErr != nil {\n\t\t\tglog.Errorf(\"load config %s error: %v\\n\", configFile, yamlErr)\n\t\t\treturn nil\n\t\t}\n\t\t// put active config\n\t\tconfig.ActiveConfig = nil\n\t\tfor _, item := range config.DC {\n\t\t\tif item.Name == config.CurrentDatacenter {\n\t\t\t\tconfig.ActiveConfig = &item\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\treturn &config\n\t}\n\tglog.Errorf(\"config %s error: %v\\n\", configFile, err)\n\treturn nil\n}", "func getConfigFilePath() string {\n\tvar configFile string\n\tflag.StringVar(&configFile, \"config\", \"./config.json\", \"JSON config file path\")\n\tflag.Parse()\n\n\tlog.Printf(\"Using config file %s\", configFile)\n\n\treturn configFile\n}", "func ParseConfig(filepath string) error {\n\tf, err := ioutil.ReadFile(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconf := make(map[string]interface{})\n\n\terr = json.Unmarshal(f, &conf)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconList := make(map[string]Elem)\n\tconfig = list{self: \"\", value: conList}\n\n\tlog.Printf(\"about to parse config\\n\")\n\tparseMap(conf, &config)\n\tlog.Printf(\"parsed config\\n\")\n\n\treturn nil\n}", "func (m *Tracing_Http) GetConfig() *types.Struct {\n\tif x, ok := m.GetConfigType().(*Tracing_Http_Config); ok {\n\t\treturn x.Config\n\t}\n\treturn nil\n}", "func (m *settings) readConfig() {\n\tlog.Printf(\"Reading configuration...\")\n\tjsonBlob, err := ioutil.ReadFile(m.filename)\n\tif err != nil {\n\t\tlog.Printf(\"No config file found. Using new config file.\")\n\t\treturn\n\t}\n\tif err := json.Unmarshal(jsonBlob, &m.redirects); err != nil {\n\t\tlog.Printf(\"Error unmarshalling %s\", err)\n\t}\n}", "func ProcessConfig() (c *Config, err error) {\n\tfile, err := os.Open(\"config.json\")\n\tif err != nil {\n\t\tlog.Println(\"Config not found in working directory, trying user's home\")\n\t\tcfgName, err2 := utils.GetHomeDirConfigFileName(\"config.json\", \".kdevpije\")\n\t\tif err2 != nil {\n\t\t\tlog.Println(\"Error obtaining home directory:\", err2)\n\t\t\treturn c, err2\n\t\t}\n\t\tvar err3 error\n\t\tfile, err3 = os.Open(cfgName)\n\t\tif err3 != nil {\n\t\t\tlog.Println(\"Config not found in ~/.kdevpije/\")\n\t\t\treturn c, err3\n\t\t}\n\t}\n\tdecoder := json.NewDecoder(file)\n\tc = &Config{}\n\terr = decoder.Decode(c)\n\tif err != nil {\n\t\tlog.Fatalln(\"Config decode error\")\n\t\treturn c, err\n\t}\n\tif c.Aliases == nil {\n\t\tc.Aliases = make(map[string][]string)\n\t}\n\tif c.PDConfig == nil {\n\t\tc.PDConfig = pagerduty.NewPDConfiguration()\n\t\tc.PDConfig.Token = \"s23zntFxLYp9NjYK99XH\"\n\t}\n\treturn\n}", "func getConfig(path string) (*config, error) {\n\tf, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcfg := &config{}\n\tif err := yaml.Unmarshal(f, &cfg); err != nil {\n\t\treturn nil, err\n\t}\n\tfmt.Println(cfg)\n\n\treturn cfg, nil\n\n}", "func ParserConfig(_struct interface{}) error {\n\tpath := \"/var/arposter/config.json\"\n\tfile, err := os.OpenFile(path, os.O_RDONLY, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\tdecoder := json.NewDecoder(file)\n\tif err := decoder.Decode(&_struct); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func readConfig(confFile, confPath, confType string) {\n\tviper.SetConfigName(confFile)\n\tviper.AddConfigPath(confPath)\n\terr := viper.ReadInConfig()\n\tif err != nil {\n\t\tfmt.Println(\"Error in reading config file. Exiting \", err.Error())\n\t\tos.Exit(1)\n\t}\n\n\t//get all config data into a conf struct\n\tConf = map[string]string{\n\t\t\"scan_success\": viper.GetString(\"common.scan_success\"),\n\t\t\"scan_failure\": viper.GetString(\"common.scan_failure\"),\n\t\t\"sort_success\": viper.GetString(\"common.sort_success\"),\n\t\t\"sort_failure\": viper.GetString(\"common.sort_failure\"),\n\t\t\"inst_name\": viper.GetString(confType + \".inst_name\"),\n\t\t\"cont\": viper.GetString(confType + \".cont\"),\n\t\t\"scan_url\": viper.GetString(confType + \".scan_url\"),\n\t\t\"sort_url\": viper.GetString(confType + \".sort_url\"),\n\t\t\"feedback_url\": viper.GetString(confType + \".feedback_url\"),\n\t\t\"wgh_url\": viper.GetString(confType + \".wgh_url\"),\n\t\t\"event_url\": viper.GetString(confType + \".event_url\"),\n\t\t\"fault_code_url\": viper.GetString(confType + \".fault_code_url\"),\n\t\t\"image_url\": viper.GetString(confType + \".image_url\"),\n\t\t\"initConfig_url\": viper.GetString(confType + \".initConfig_url\"),\n\t}\n\tfor k, v := range Conf {\n\t\tfmt.Printf(\"%s : %s\\n\", k, v)\n\t}\n}", "func GetConfig() Config {\n\tif value, ok := os.LookupEnv(\"APP_DEBUG\"); ok {\n\t\tvalue = strings.Trim(value, \" \\r\\n\")\n\t\tvalue = strings.ToLower(value)\n\t\tif value == \"true\" {\n\t\t\tconfig.Debug = true\n\t\t} else {\n\t\t\tgin.SetMode(gin.ReleaseMode)\n\t\t}\n\t}\n\n\tif value, ok := os.LookupEnv(\"GEO_IP_DB_PATH\"); ok {\n\t\tvalue = strings.Trim(value, \" \\r\\n\")\n\t\tconfig.GeoIP.DBPath = value\n\t} else {\n\t\t// log.Fatalln(\"GEO_IP_DB_PATH is not set\")\n\t}\n\n\tif value, ok := os.LookupEnv(\"REQUEST_ID_LENGTH\"); ok {\n\t\tif length, err := strconv.Atoi(value); err == nil {\n\t\t\tconfig.RequestID.Length = length\n\t\t}\n\t}\n\n\treturn config\n}", "func (app *Application) GetConfig() *Config {\n return app.config\n}", "func ParseFile(configFilePath string) (*Config, error) {\n\t// Read the config file\n\tconfigData, err := ioutil.ReadFile(configFilePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Parse the config JSON\n\tconfig := Config{}\n\terr = json.Unmarshal(configData, &config)\n\tif err != nil {\n\t\treturn nil, errors.New(\"invalid config file\")\n\t}\n\n\t// Validate the ports\n\tif config.TelnetPort <= 0 {\n\t\treturn nil, errors.New(\"invalid telnet port\")\n\t}\n\n\tif config.WebPort <= 0 {\n\t\treturn nil, errors.New(\"invalid web port\")\n\t}\n\n\t// Validate the web client path\n\tinfo, err := os.Stat(config.WebClientPath)\n\tif (err != nil && os.IsNotExist(err)) || !info.IsDir() {\n\t\treturn nil, errors.New(\"invalid web client path\")\n\t}\n\n\treturn &config, nil\n}", "func GetWebConfig(w http.ResponseWriter, r *http.Request) {\n\tmiddleware.EnableCors(&w)\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\tconfiguration := config.Config.InstanceDetails\n\tconfiguration.Version = config.Config.VersionInfo\n\tif err := json.NewEncoder(w).Encode(configuration); err != nil {\n\t\tbadRequestHandler(w, err)\n\t}\n}", "func GetConfig() Configuration{\n\tcurrentPath := files.GetCurrentDirectory()\n\tjsonFile, err := os.Open(currentPath + \"/config.json\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tfmt.Println(currentPath)\n\tdefer jsonFile.Close()\n\tbyteValue, _ := ioutil.ReadAll(jsonFile)\n\tvar configuration Configuration\n\tjson.Unmarshal(byteValue, &configuration)\n\treturn configuration\n}", "func configRead() (string, error) {\n\n\tfhndl, err := ioutil.ReadFile(\"/etc/testpool/testpool.yml\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\troot, err := simpleyaml.NewYaml(fhndl)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvalue := root.GetPath(\"tpldaemon\", \"profile\", \"log\")\n\treturn value.String()\n\n}", "func ConfigReadFile(path string) (string, []byte, error) {\n\tif strings.HasPrefix(path, \"file://\") {\n\t\tpath = path[7:]\n\t}\n\n\tpos := strings.LastIndexByte(path, '.')\n\tif pos == -1 {\n\t\tpos += len(path)\n\t}\n\n\tdata, err := ioutil.ReadFile(path)\n\tlast := strings.LastIndex(path, \".\") + 1\n\tif last == 0 {\n\t\treturn \"\", nil, fmt.Errorf(\"read file config, type is null\")\n\t}\n\treturn path[pos+1:], data, err\n}", "func GetConfig(configFileName string, trafficOpsHost string, trafficServerHost string, params []TrafficOpsParameter) (string, error) {\n\tswitch configFileName {\n\tcase \"storage.config\":\n\t\treturn createStorageDotConfig(trafficOpsHost, trafficServerHost, params)\n\tdefault:\n\t\treturn \"\", errors.New(\"Config file '%s' not valid\")\n\t}\n}", "func (c ConfigHandler) GetConfig(key string, defaultValue interface{}) interface{} {\n\t// Returns the default value if the key is not defined in the config\n\tif c.config.IsSet(key) == false {\n\t\treturn defaultValue\n\t}\n\treturn c.config.Get(key)\n}", "func getConfig(fpath string) {\n\traw, err := ioutil.ReadFile(fpath)\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to read config %q, err: %v\", fpath, err)\n\t\tos.Exit(1)\n\t}\n\terr = json.Unmarshal(raw, &ctx.config)\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to json-unmarshal config %q, err: %v\", fpath, err)\n\t\tos.Exit(1)\n\t}\n}", "func (client *WANCableLinkConfig1) GetConfigFile() (NewConfigFile string, err error) {\n\treturn client.GetConfigFileCtx(context.Background())\n}", "func getConfig(configFile string) {\n\tvar err error\n\tvar input = io.ReadCloser(os.Stdin)\n\tif input, err = os.Open(configFile); err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tdefer input.Close()\n\n\t// Read the config file\n\tyamlBytes, err := ioutil.ReadAll(input)\n\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\t// Parse the config\n\tif err := yaml.Unmarshal(yamlBytes, &config); err != nil {\n\t\t//log.Fatalf(\"Content: %v\", yamlBytes)\n\t\tlog.Fatalf(\"Could not parse %q: %v\", configFile, err)\n\t}\n}", "func (b *backend) pathConfigRead(ctx context.Context, req *logical.Request, _ *framework.FieldData) (*logical.Response, error) {\n\tc, err := b.GetConfig(ctx, req.Storage)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &logical.Response{\n\t\tData: map[string]interface{}{\n\t\t\t\"endpoint\": c.Endpoint,\n\t\t\t\"accessKeyId\": c.AccessKeyId,\n\t\t\t\"secretAccessKey\": c.SecretAccessKey,\n\t\t\t\"useSSL\": c.UseSSL,\n\t\t},\n\t}, nil\n}", "func (o *FormField) GetConfig() FormConfig {\n\tif o == nil || o.Config == nil {\n\t\tvar ret FormConfig\n\t\treturn ret\n\t}\n\treturn *o.Config\n}", "func GetConfig() *PinoyConfig {\n\treturn pcfg\n}", "func readParseFile(filename string) (page Page) {\n\tlog.Debug(\"Parsing File:\", filename)\n\tepoch, _ := time.Parse(\"20060102\", \"19700101\")\n\n\t// setup default page struct\n\tpage = Page{\n\t\tDate: epoch,\n\t\tOutFile: filename,\n\t\tExtension: \".html\",\n\t\tParams: make(map[string]string),\n\t}\n\n\t// read file\n\tvar data, err = ioutil.ReadFile(filename)\n\tif err != nil {\n\t\tlog.Warn(\"Error Reading: \" + filename)\n\t\treturn\n\t}\n\n\t// go through content parse from --- to ---\n\tvar lines = strings.Split(string(data), \"\\n\")\n\tvar found = 0\n\tfor i, line := range lines {\n\t\tline = strings.TrimSpace(line)\n\n\t\tif found == 1 {\n\t\t\t// parse line for param\n\t\t\tcolonIndex := strings.Index(line, \":\")\n\t\t\tif colonIndex > 0 {\n\t\t\t\tkey := strings.ToLower(strings.TrimSpace(line[:colonIndex]))\n\t\t\t\tvalue := strings.TrimSpace(line[colonIndex+1:])\n\t\t\t\tvalue = strings.Trim(value, \"\\\"\") //remove quotes\n\t\t\t\tswitch key {\n\t\t\t\tcase \"title\":\n\t\t\t\t\tpage.Title = value\n\t\t\t\tcase \"category\":\n\t\t\t\t\tpage.Category = value\n\t\t\t\tcase \"layout\":\n\t\t\t\t\tpage.Layout = value\n\t\t\t\tcase \"extension\":\n\t\t\t\t\tpage.Extension = \".\" + value\n\t\t\t\tcase \"date\":\n\t\t\t\t\tpage.Date, _ = time.Parse(\"2006-01-02\", value[0:10])\n\t\t\t\tdefault:\n\t\t\t\t\tpage.Params[key] = value\n\t\t\t\t}\n\t\t\t}\n\n\t\t} else if found >= 2 {\n\t\t\t// params over\n\t\t\tlines = lines[i:]\n\t\t\tbreak\n\t\t}\n\n\t\tif line == \"---\" {\n\t\t\tfound += 1\n\t\t}\n\n\t}\n\n\t// chop off first directory, since that is the template dir\n\tlog.Debug(\"Filename\", filename)\n\tpage.OutFile = filename[strings.Index(filename, string(os.PathSeparator))+1:]\n\tpage.OutFile = strings.Replace(page.OutFile, \".md\", page.Extension, 1)\n\tlog.Debug(\"page.Outfile\", page.OutFile)\n\n\t// next directory(s) category, category includes sub-dir = solog/webdev\n\tif page.Category == \"\" {\n\t\tif strings.Contains(page.OutFile, string(os.PathSeparator)) {\n\t\t\tpage.Category = page.OutFile[0:strings.LastIndex(page.OutFile, string(os.PathSeparator))]\n\t\t\tpage.SimpleCategory = strings.Replace(page.Category, string(os.PathSeparator), \"_\", -1)\n\t\t}\n\t}\n\tlog.Debug(\"page.Category\", page.Category)\n\t// parse date from filename\n\tbase := filepath.Base(page.OutFile)\n\tif base[0:2] == \"20\" || base[0:2] == \"19\" { //HACK: if file starts with 20 or 19 assume date\n\t\tpage.Date, _ = time.Parse(\"2006-01-02\", base[0:10])\n\t\tpage.OutFile = strings.Replace(page.OutFile, base[0:11], \"\", 1) // remove date from final filename\n\t}\n\n\t// add url of page, which includes initial slash\n\t// this is needed to get correct links for multi\n\t// level directories\n\tpage.Url = \"/\" + page.OutFile\n\n\t// convert markdown content\n\tcontent := strings.Join(lines, \"\\n\")\n\tif (config.UseMarkdown) && (page.Params[\"markdown\"] != \"no\") {\n\t\toutput := blackfriday.Run([]byte(content))\n\t\tpage.Content = string(output)\n\t} else {\n\t\tpage.Content = content\n\t}\n\n\treturn page\n}", "func parseConfig(path string) (Config, error) {\n\tconfig := Config{}\n\tfile, err := os.Open(path)\n\tdefer file.Close()\n\tif err != nil {\n\t\treturn config, err\n\t}\n\tdecoder := json.NewDecoder(file)\n\terr = decoder.Decode(&config)\n\tif err != nil {\n\t\treturn config, err\n\t}\n\treturn config, nil\n}", "func (p *Parser) Get(config interface{}) error {\n\tv := reflect.ValueOf(config)\n\tif t := v.Type(); !(t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct) {\n\t\treturn NewErrInvalidConfigType(t)\n\t}\n\n\t_, err := p.parse(v.Elem())\n\n\treturn err\n}", "func GetConfig(fileName string) (*MatterwickConfig, error) {\n\tconfig := &MatterwickConfig{}\n\tfileName = findConfigFile(fileName)\n\n\tfile, err := os.Open(fileName)\n\tif err != nil {\n\t\treturn config, errors.Wrap(err, \"unable to open config file\")\n\t}\n\n\tdecoder := json.NewDecoder(file)\n\terr = decoder.Decode(config)\n\tif err != nil {\n\t\treturn config, errors.Wrap(err, \"unable to decode config file\")\n\t}\n\n\treturn config, nil\n}", "func GetConfig(item string) string {\n\tswitch item {\n\tcase \"dbtouse\":\n\t\treturn Conf.Dbtouse\n\tcase \"dburl\":\n\t\treturn Conf.Dburl\n\tcase \"connectString\":\n\t\treturn Conf.ConnectString\n\tcase \"Mapsfile\":\n\t\treturn Conf.Mapsfile\n\tcase \"Templatesdir\":\n\t\treturn Conf.Templatesdir\n\tcase \"Tcpport\":\n\t\treturn Conf.Tcpport\n\tcase \"Fnr\":\n\t\treturn fmt.Sprintf(\"%v\", Conf.Fnr)\n\t}\n\treturn \"unknown request\"\n}", "func GetConfig(myCfg string, tolerant, allowSourcing, expand, recursive bool, expandMap map[string]string) map[string]string {\n\tif len(expandMap) > 0 {\n\t\texpand = true\n\t} else {\n\t\texpandMap = map[string]string{}\n\t}\n\tmyKeys := map[string]string{}\n\n\tif recursive {\n\t\tif !expand {\n\t\t\texpandMap = map[string]string{}\n\t\t}\n\t\tfname := \"\"\n\t\tfor _, fname = range grab.RecursiveFileList(myCfg) {\n\t\t\tnewKeys := GetConfig(fname, tolerant, allowSourcing, true, false, expandMap)\n\t\t\tfor k, v := range newKeys {\n\t\t\t\tmyKeys[k] = v\n\t\t\t}\n\t\t}\n\t\tif fname == \"\" {\n\t\t\treturn nil\n\t\t}\n\t\treturn myKeys\n\t}\n\n\tf, err := os.Open(myCfg)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tf.Close()\n\tc, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tcontent := string(c)\n\n\tif content != \"\" && !strings.HasSuffix(content, \"\\n\") {\n\t\tcontent += \"\\n\"\n\t}\n\tif strings.Contains(content, \"\\r\") {\n\t\tmsg.WriteMsg(fmt.Sprintf(\"!!! Please use dos2unix to convert line endings in config file: '%s'\\n\", myCfg), -1, nil)\n\t}\n\tlex := NewGetConfigShlex(strings.NewReader(content), myCfg, true, \"\", tolerant)\n\tlex.Wordchars = \"abcdfeghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789~!@#$%*_\\\\:;?,./-+{}\"\n\tlex.Quotes = \"\\\"'\"\n\tif allowSourcing {\n\t\tlex.allowSourcing(expandMap)\n\t}\n\tfor {\n\t\tkey, _ := lex.GetToken()\n\t\tif key == \"export\" {\n\t\t\tkey, _ = lex.GetToken()\n\t\t}\n\t\tif key == \"\" {\n\t\t\tbreak\n\t\t}\n\t\tequ, _ := lex.GetToken()\n\t\tif equ == \"\" {\n\t\t\tmsg1 := \"Unexpected EOF\" //TODO error_leader\n\t\t\tif !tolerant {\n\t\t\t\t//raise ParseError(msg)\n\t\t\t} else {\n\t\t\t\tmsg.WriteMsg(fmt.Sprintf(\"%s\\n\", msg1), -1, nil)\n\t\t\t\treturn myKeys\n\t\t\t}\n\t\t} else if equ != \"=\" {\n\t\t\tmsg1 := fmt.Sprintf(\"Invalid token '%s' (not '=')\", equ) //TODO error_leader\n\t\t\tif !tolerant {\n\t\t\t\t//raise ParseError(msg)\n\t\t\t} else {\n\t\t\t\tmsg.WriteMsg(fmt.Sprintf(\"%s\\n\", msg1), -1, nil)\n\t\t\t\treturn myKeys\n\t\t\t}\n\t\t}\n\t\tval, _ := lex.GetToken() /* TODO: fix it\n\t\tif val == \"\" {\n\t\t\tmsg := fmt.Sprintf(\"Unexpected end of config file: variable '%s'\", key) //TODO error_leader\n\t\t\tif !tolerant {\n\t\t\t\t//raise ParseError(msg)\n\t\t\t} else {\n\t\t\t\tmsg.WriteMsg(fmt.Sprintf(\"%s\\n\", msg), -1, nil)\n\t\t\t\treturn myKeys\n\t\t\t}\n\t\t}*/\n\t\tif invalidVarNameRe.MatchString(key) {\n\t\t\tmsg1 := fmt.Sprintf(\"Invalid variable name '%s'\", key) //TODO error_leader\n\t\t\tif !tolerant {\n\t\t\t\t//raise ParseError(msg)\n\t\t\t} else {\n\t\t\t\tmsg.WriteMsg(fmt.Sprintf(\"%s\\n\", msg1), -1, nil)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tif expand {\n\t\t\tmyKeys[key] = VarExpand(val, expandMap, nil) //TODO lex.error_leader\n\t\t\texpandMap[key] = myKeys[key]\n\t\t} else {\n\t\t\tmyKeys[key] = val\n\t\t}\n\t}\n\treturn myKeys\n}", "func GetConfig() *Config {\n\tvar configPath string\n\tflag.StringVar(&configPath, \"config-path\", \"../configs/server.toml\", \"config file path\")\n\tflag.Parse()\n\tconfig := NewConfig()\n\t_, err := toml.DecodeFile(configPath, config)\n\tHandleError(err, ErrorFatal)\n\treturn config\n}", "func (a *Admin) GetConfig(_ *http.Request, _ *struct{}, reply *interface{}) error {\n\ta.Log.Debug(\"API called\",\n\t\tzap.String(\"service\", \"admin\"),\n\t\tzap.String(\"method\", \"getConfig\"),\n\t)\n\t*reply = a.NodeConfig\n\treturn nil\n}", "func GetConfig(filename string) Config {\n\tconfig := Config{}\n\n\tdata, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = json.Unmarshal(data, &config)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn config\n}", "func GetConfig() *viper.Viper {\n\treturn config\n}", "func (b *Backend) GetConfig() string {\n\tvar sb strings.Builder\n\tsb.WriteString(\"name \" + b.Config.Name + \"\\n\")\n\tsb.WriteString(\"method \" + b.Config.Method + \"\\n\")\n\tsb.WriteString(\"realm \" + b.Config.Realm + \"\\n\")\n\tsb.WriteString(\"provider \" + b.Config.Provider)\n\treturn sb.String()\n}", "func (c *Config) Get(path string) Value {\n\tc.l.RLock()\n\tdefer c.l.RUnlock()\n\n\treturn Value{\n\t\traw: reduce(strings.Split(path, \".\"), c.m),\n\t}\n}", "func (p *Plugin) getConfigData(ctx context.Context, req *request) (string, error) {\n\t// get changed files\n\tchangedFiles, err := p.getScmChanges(ctx, req)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// get drone.yml for changed files or all of them if no changes/cron\n\tconfigData := \"\"\n\tif changedFiles != nil {\n\t\tconfigData, err = p.getConfigForChanges(ctx, req, changedFiles)\n\t} else if req.Build.Trigger == \"@cron\" {\n\t\tlogrus.Warnf(\"%s @cron, rebuilding all\", req.UUID)\n\t\tif p.considerFile == \"\" {\n\t\t\tlogrus.Warnf(\"recursively scanning for config files with max depth %d\", p.maxDepth)\n\t\t}\n\t\tconfigData, err = p.getConfigForTree(ctx, req, \"\", 0)\n\t} else if p.fallback {\n\t\tlogrus.Warnf(\"%s no changed files and fallback enabled, rebuilding all\", req.UUID)\n\t\tif p.considerFile == \"\" {\n\t\t\tlogrus.Warnf(\"recursively scanning for config files with max depth %d\", p.maxDepth)\n\t\t}\n\t\tconfigData, err = p.getConfigForTree(ctx, req, \"\", 0)\n\t}\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// no file found\n\tif configData == \"\" {\n\t\treturn \"\", errors.New(\"did not find a .drone.yml\")\n\t}\n\n\t// cleanup\n\tconfigData = removeDocEndRegex.ReplaceAllString(configData, \"\")\n\tconfigData = string(dedupRegex.ReplaceAll([]byte(configData), []byte(\"---\")))\n\treturn configData, nil\n}", "func (c *Config) ReadConfig(configPath string) {\n\t// Init viper\n\tc.v = viper.New()\n\n\t// Init maps where the config will be stored\n\tc.strings = make(map[string]string)\n\tc.booleans = make(map[string]bool)\n\tc.uints = make(map[string]uint)\n\n\t// Define where viper tries to get config information\n\tenvPrefix := \"sprawl\"\n\n\t// Set environment variable prefix, automatically transformed to uppercase\n\tc.v.SetEnvPrefix(envPrefix)\n\n\t// Set replacer to env variables, replacing dots with underscores\n\tc.v.SetEnvKeyReplacer(strings.NewReplacer(\".\", \"_\"))\n\n\t// Automatically try to fetch all configs from env\n\tc.v.AutomaticEnv()\n\n\t// Initialize viper with Sprawl-specific options\n\tc.v.SetConfigName(\"config\")\n\n\t// Use toml format for config files\n\tc.v.SetConfigType(\"toml\")\n\n\t// Allow build to disable config file directories\n\tif configPath != \"\" {\n\t\t// Check for overriding config files\n\t\tc.v.AddConfigPath(\".\")\n\t\t// Check for user submitted config path\n\t\tc.v.AddConfigPath(configPath)\n\t}\n\n\t// Read config file\n\tif err := c.v.ReadInConfig(); !errors.IsEmpty(err) {\n\t\tif _, ok := err.(viper.ConfigFileNotFoundError); ok {\n\t\t\tfmt.Println(\"Config file not found, using ENV\")\n\t\t} else {\n\t\t\tfmt.Println(\"Config file invalid!\")\n\t\t}\n\t} else {\n\t\tfmt.Println(\"Config successfully loaded.\")\n\t}\n\n\tc.AddString(dbPathVar)\n\tc.AddString(p2pExternalIPVar)\n\tc.AddString(logLevelVar)\n\tc.AddString(logFormatVar)\n\tc.AddUint(p2pPortVar)\n\tc.AddUint(rpcPortVar)\n\tc.AddUint(websocketPortVar)\n\tc.AddBoolean(websocketEnableVar)\n\tc.AddBoolean(dbInMemoryVar)\n\tc.AddBoolean(p2pNATPortMapVar)\n\tc.AddBoolean(p2pRelayVar)\n\tc.AddBoolean(p2pAutoRelayVar)\n\tc.AddBoolean(p2pDebugVar)\n\tc.AddBoolean(errorsEnableStackTraceVar)\n\tc.AddBoolean(ipfsPeerVar)\n\n}", "func Get(path ...string) reader.Value {\n\treturn DefaultConfig.Get(normalizePath(path...)...)\n}", "func (p *Plugin) getConfig(ctx context.Context, req *request) (*drone.Config, error) {\n\tlogrus.WithFields(logrus.Fields{\n\t\t\"after\": req.Build.After,\n\t\t\"before\": req.Build.Before,\n\t\t\"branch\": req.Repo.Branch,\n\t\t\"ref\": req.Build.Ref,\n\t\t\"slug\": req.Repo.Slug,\n\t\t\"trigger\": req.Build.Trigger,\n\t}).Debugf(\"drone-tree-config environment\")\n\n\t// check cache first, when enabled\n\tck := newCacheKey(req)\n\tif p.cacheTTL > 0 {\n\t\tif cached, exists := p.cache.retrieve(req.UUID, ck); exists {\n\t\t\tif cached != nil {\n\t\t\t\treturn &drone.Config{Data: cached.config}, cached.error\n\t\t\t}\n\t\t}\n\t}\n\n\t// fetch the config data. cache it, when enabled\n\treturn p.cacheAndReturn(\n\t\treq.UUID, ck,\n\t\tnewCacheEntry(\n\t\t\tp.getConfigData(ctx, req),\n\t\t),\n\t)\n}", "func GetConfig(section string, option string) string {\n value, err := cfg.String(section, option)\n if err != nil {\n seelog.Errorf(\"Get Config [%v].[%v] Fail : %v\", section, option, err)\n return \"\"\n }\n\n return value\n // result is string \"http://www.example.com/some/path\"\n\n // c.Int(\"service-1\", \"maxclients\")\n // // result is int 200\n\n // c.Bool(\"service-1\", \"delegation\")\n // // result is bool true\n\n // c.String(\"service-1\", \"comments\")\n // // result is string \"This is a multi-line\\nentry\"\n}", "func (c *ConfigImpl) GetConfig(key string) (GoConfig, error) {\n\tkeys := strings.Split(key, \".\")\n\tvalues := subMap(&c.values, keys, false)\n\tif nil == values {\n\t\treturn nil, errors.New(\"Key '\" + key + \"' does not exsists\")\n\t}\n\treturn &ConfigImpl{values: *values, parent: c, def: c.def}, nil\n}", "func GetConfig() interface{} {\n\treturn std.GetConfig()\n}", "func GetConfig(returnType, key string, defaultVal interface{}) (value interface{}, err error) {\n\tsection, err := config.GetSection(returnType)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif section[key] != \"\" {\n\t\treturn section[key], nil\n\t}\n\treturn defaultVal, nil\n}", "func (s *ossServer) parseConfig(path string) (*dataRun.Config, error) {\n\tpath = s.resolvePath(path)\n\t// Use demo configuration if no config path is specified.\n\tif path == \"\" {\n\t\treturn nil, errors.New(\"missing config file\")\n\t}\n\n\tconfig := dataRun.NewConfig()\n\tif err := config.FromTomlFile(path); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn config, nil\n}", "func GetConfig() {\n\n\tenv := true\n\ttempcfgdbhostname := os.Getenv(\"APP_DB_HOSTNAME\")\n\ttempcfgport := os.Getenv(\"APP_PORT\")\n\tif tempcfgdbhostname != \"\" {\n\t\tglobalconfig.DBHostName = tempcfgdbhostname\n\t} else {\n\t\tenv = false\n\t}\n\tif tempcfgport != \"\" {\n\t\tglobalconfig.HTTPPortNumber = tempcfgport\n\t} else {\n\t\tenv = false\n\t}\n\n\tif env == false {\n\t\tconfigbytes, err := ioutil.ReadFile(\"config.json\")\n\t\tif err != nil {\n\t\t}\n\t\terr = json.Unmarshal(configbytes, &globalconfig)\n\t\tfmt.Println(globalconfig)\n\t\tif err == nil {\n\t\t\tglobalconfig.Method = \"CofigFile\"\n\t\t}\n\t} else {\n\t\tglobalconfig.Method = \"EnvironmentVars\"\n\t}\n}", "func (c *Config) File() string { return c.viper.GetString(configFile) }", "func (m *HealthCheck_CustomHealthCheck) GetConfig() *types.Struct {\n\tif x, ok := m.GetConfigType().(*HealthCheck_CustomHealthCheck_Config); ok {\n\t\treturn x.Config\n\t}\n\treturn nil\n}", "func GetConfig() (config *Config, err error) {\n\tconfigpath := path.Join(os.Getenv(\"GOPATH\"), \"src\", \"hellofresh\", \"config.json\")\n\tconfigFile, err := os.Open(configpath)\n\tdefer configFile.Close()\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tjsonParser := json.NewDecoder(configFile)\n\tif err = jsonParser.Decode(&config); err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func GetRecalboxConfHandler(ctx iris.Context) {\n\tcp := viper.GetString(\"recalbox.confPath\")\n\tcc, err := ioutil.ReadFile(cp)\n\tif err != nil {\n\t\tctx.Values().Set(\"error\", errors.FormatErrorForLog(ctx, err.(error)))\n\t\tctx.StatusCode(500)\n\n\t\treturn\n\t}\n\n\tctx.ViewData(\"ConfPath\", cp)\n\tctx.ViewData(\"ConfContent\", string(cc))\n\n\tctx.ViewData(\"Tr\", iris.Map{\n\t\t\"BtnSave\": ctx.Translate(\"BtnSave\"),\n\t})\n\n\tctx.View(\"views/recalbox-conf.pug\")\n}", "func (c *config) GetConfig(key string, res interface{}) (err error) {\n\tvar (\n\t\treq *http.Request\n\t\tresp *http.Response\n\t\tbs []byte\n\t)\n\tif key != \"\" {\n\t\tc.Key = key\n\t}\n\tif req, err = http.NewRequest(\"GET\", c.buildUrl(), nil); err != nil {\n\t\treturn\n\t}\n\tclient := http.Client{}\n\tif resp, err = client.Do(req); err != nil {\n\t\treturn\n\t}\n\tif resp.StatusCode == http.StatusNotFound {\n\t\terr = ConfigNotFound\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\tif bs, err = readAll(resp.Body, _minRead); err != nil {\n\t\treturn\n\t}\n\t_, err = toml.Decode(string(bs), res)\n\treturn\n}", "func (b *TendermintBackend) parseConfig() (*cfg.Config, error) {\n\tv := viper.New()\n\tv.AutomaticEnv()\n\n\tv.SetEnvPrefix(\"TM\")\n\tv.SetConfigName(\"config\") // name of config file (without extension)\n\tv.AddConfigPath(b.RootPath + \"/config\") // search root directory\n\tv.ReadInConfig()\n\tconf := cfg.DefaultConfig()\n\terr := v.Unmarshal(conf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconf.SetRoot(b.RootPath)\n\t//Add overrides here\n\tif b.OverrideCfg.RPCListenAddress != \"\" {\n\t\tconf.RPC.ListenAddress = b.OverrideCfg.RPCListenAddress\n\t}\n\tconf.ProxyApp = fmt.Sprintf(\"tcp://127.0.0.1:%d\", b.OverrideCfg.RPCProxyPort)\n\tconf.Consensus.CreateEmptyBlocks = b.OverrideCfg.CreateEmptyBlocks\n\tconf.Mempool.WalPath = \"data/mempool.wal\"\n\n\tcfg.EnsureRoot(b.RootPath)\n\treturn conf, err\n}", "func GetConfig() *Config {\n\treturn &values\n}", "func parseConfig(appConfigPath string) (err error) {\n\tAppConfig, err = newAppConfig(appConfigProvider, appConfigPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn assignConfig(AppConfig)\n}", "func parseConfig(appConfigPath string) (err error) {\n\tAppConfig, err = newAppConfig(appConfigProvider, appConfigPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn assignConfig(AppConfig)\n}", "func readConfig(file string) wConfig {\n\tvar c = wConfig{}\n\t_, err := os.Stat(file)\n\tif err == nil {\n\t\tf, _ := os.Open(file)\n\t\tdefer f.Close()\n\t\tdecoder := json.NewDecoder(f)\n\t\terr := decoder.Decode(&c)\n\t\tcheck(err)\n\t} else {\n\t\tif !os.IsNotExist(err) {\n\t\t\tlog.Fatalf(\"Unable to read %s: %s\\n\", file, err)\n\t\t}\n\t}\n\treturn c\n}", "func GetConfigFile() (string, string) {\n\tdefaultConfig := filepath.Join(file.UserHome(), config.DefaultConfigDir, config.DefaultConfig)\n\tdefaultAppDir, _ := filepath.Split(defaultConfig)\n\treturn defaultAppDir, defaultConfig\n}", "func (db *DB) readConfig() (*ConfigEntry, error) {\n\tdata, err := ioutil.ReadFile(db.ConfigPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar entries map[string]ConfigEntry\n\terr = yaml.Unmarshal(data, &entries)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tentry, exists := entries[db.Domain]\n\tif !exists {\n\t\treturn nil, ErrNotFound\n\t}\n\n\treturn &entry, nil\n}", "func (configProvider) GetProjectConfig(c context.Context, p string) (*tricium.ProjectConfig, error) {\n\treturn getProjectConfig(c, p)\n}", "func GetConfig(useGCPSecrets bool,\n\tyamlConfig bool, jsonConfig bool,\n\tfilePath string, config interface{}) error {\n\tvar data []byte\n\tvar err error\n\tif yamlConfig && jsonConfig {\n\t\treturn errors.New(\"yamlconfig and jsonconfig cannot both be true\")\n\t}\n\n\tif useGCPSecrets {\n\t\tgcloudVars := setGcloudVars()\n\t\tdata, err = gcloudVars.getSecretFromGSM()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tdata, err = ioutil.ReadFile(filePath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif yamlConfig {\n\t\terr = yaml.Unmarshal([]byte(data), &config)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else if jsonConfig {\n\t\terr = json.Unmarshal([]byte(data), &config)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func GetConfig() Config {\n\tif !loaded {\n\t\tbyteData, err := ioutil.ReadFile(\"config.json\")\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tjson.Unmarshal(byteData, &config)\n\t\tloaded = true\n\t}\n\treturn config\n}", "func parseConfig(file *os.File) (Config, error) {\n\tbuilderConfig := Config{}\n\ttomlMetadata, err := toml.NewDecoder(file).Decode(&builderConfig)\n\tif err != nil {\n\t\treturn Config{}, errors.Wrap(err, \"decoding toml contents\")\n\t}\n\n\tundecodedKeys := tomlMetadata.Undecoded()\n\tif len(undecodedKeys) > 0 {\n\t\tunknownElementsMsg := config.FormatUndecodedKeys(undecodedKeys)\n\n\t\treturn Config{}, errors.Errorf(\"%s in %s\",\n\t\t\tunknownElementsMsg,\n\t\t\tstyle.Symbol(file.Name()),\n\t\t)\n\t}\n\n\treturn builderConfig, nil\n}", "func GetAppConfiguration() map[string] interface{} {\r\n\tif (appConfig != nil) {\r\n\t\treturn appConfig;\r\n\t}\r\n\r\n\tdir, _ := os.Getwd();\r\n\tplan, _ := ioutil.ReadFile(dir + \"/conf/config.json\") // filename is the JSON file to read\r\n\tvar data map[string] interface{}\r\n\terr := json.Unmarshal(plan, &data)\r\n\tif (err != nil) {\r\n\t\tpanic(err)\r\n\t}\r\n\r\n\tappConfig = data;\r\n\tprintConfig();\r\n\treturn data;\r\n}", "func (p Plans) ConfigFile() Path {\n\treturn p.Expand().Join(\"config.json\")\n}", "func ParseConfigFile(filePath string) (*Config, error) {\n\tv := viper.New()\n\tcfg := &Config{v}\n\tcfg.SetDefault(\"init\", \"\") // e.g. \"init.sh\"\n\tcfg.SetDefault(\"run\", \"\") // e.g. \"run.sh\"\n\tcfg.SetDefault(\"clean\", \"\") // e.g. \"clean.sh\"\n\tcfg.SetDefault(\"validate\", \"\") // e.g. \"validate.sh\"\n\tcfg.SetDefault(\"kill\", \"\") // e.g. \"kill.sh\", unexpected death\n\tcfg.SetDefault(\"shutdown\", \"\") // e.g. \"shutdown.sh\", graceful shutdown\n\tcfg.SetDefault(\"explorePolicy\", \"dumb\")\n\tcfg.SetDefault(\"explorePolicyParam\", map[string]interface{}{})\n\tcfg.SetDefault(\"storageType\", \"naive\")\n\tcfg.SetDefault(\"notCleanIfValidationFail\", false)\n\t// Viper Issue: Default value for nested key #71 (https://github.com/spf13/viper/issues/71)\n\tcfg.SetDefault(\"inspectorHandler\",\n\t\tmap[string]interface{}{\n\t\t\t\"pb\": map[string]interface{}{\n\t\t\t\t// TODO: port\n\t\t\t},\n\t\t\t\"rest\": map[string]interface{}{\n\t\t\t\t// TODO: port\n\t\t\t},\n\t\t})\n\t// viper supports JSON, YAML, and TOML\n\tcfg.SetConfigFile(filePath)\n\terr := cfg.ReadInConfig()\n\tif err == nil {\n\t\tif cfg.GetString(\"run\") == \"\" {\n\t\t\terr = errors.New(\"required field \\\"run\\\" is missing\")\n\t\t}\n\t}\n\treturn cfg, err\n}", "func (n Node) GetConfig() *TreeConfig {\n\treturn n.GetRoot().Config\n}", "func readConfig(configFilePath string) *Config {\n\t// fmt.Println(\"doing readConfig\")\n\tfile, err := os.Open(configFilePath)\n\tdefer file.Close()\n\tdecoder := json.NewDecoder(file)\n\tconfig := new(Config)\n\terr = decoder.Decode(config)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn config\n}", "func GetConfig() *Config {\n\treturn &Config{\n\t\tDB: &DBConfig{\n\t\t\tUsername: \"postgres\",\n\t\t\tPassword: \"cristiano1994\",\n\t\t\tDatabase: \"spataro_visitas\",\n\t\t\tPort: 5432,\n\t\t\tHost: \"localhost\",\n\t\t},\n\t}\n}", "func GetConfig() *viper.Viper {\n\tviper.SetConfigName(\"base\")\n\tviper.AddConfigPath(\"config\")\n\tif err := viper.ReadInConfig(); err != nil {\n\t\tif _, ok := err.(viper.ConfigFileNotFoundError); ok {\n\t\t\tlog.Fatal(\"Config file not found\")\n\t\t} else {\n\t\t\tlog.Fatal( \"Config file can't be read\")\n\t\t}\n\t}\n\treturn viper.GetViper()\n}", "func GetConfig() (map[string]string, error) {\n\tdata, err := download(GcpConfigFileName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar config map[string]string\n\terr = json.Unmarshal(data, &config)\n\treturn config, err\n}", "func readConfigFile(cfgFile string) (Config, error) {\n\n\tlog.Info(\"RabbitRelay: reading configuration from: \", cfgFile)\n\n\tconfig := Config{}\n\n\tvar err error\n\tfileContents, err := ioutil.ReadFile(cfgFile)\n\n\tif err != nil {\n\n\t\tlog.Critical(\"Error reading config file: \", err)\n\n\t} else {\n\n\t\t// This doesn't work, only the top level items are populated\n\t\t// err = jsonpointer.FindDecode(fileContents,\"\",&config)\n\t\terr = jsonpointer.FindDecode(fileContents, \"/masterRabbitServer\", &config.masterServer)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Error reading master server config: \", err)\n\t\t\treturn config, err\n\t\t}\n\t\terr = jsonpointer.FindDecode(fileContents, \"/slaveRabbitServers\", &config.slaveServers)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Error reading slave server config: \", err)\n\t\t\treturn config, err\n\t\t}\n\t}\n\treturn config, err\n}", "func GetConfig() Config {\n\tport, ok := os.LookupEnv(\"PORT\")\n\tif !ok {\n\t\tport = \"8080\"\n\t}\n\n\tenv, ok := os.LookupEnv(\"ENV\")\n\tif !ok {\n\t\tenv = \"development\"\n\t}\n\n\tpgHost, ok := os.LookupEnv(\"PG_HOST\")\n\tif !ok {\n\t\tpgHost = \"localhost\"\n\t}\n\n\tpgPort, ok := os.LookupEnv(\"PG_PORT\")\n\tif !ok {\n\t\tpgPort = \"5432\"\n\t}\n\n\tpgUser, ok := os.LookupEnv(\"PG_USER\")\n\tif !ok {\n\t\tpgUser = \"postgres\"\n\t}\n\n\tpgPassword, ok := os.LookupEnv(\"PG_PASSWORD\")\n\tif !ok {\n\t\tpgPassword = \"\"\n\t}\n\n\tpgDBName, ok := os.LookupEnv(\"PG_DB_NAME\")\n\tif !ok {\n\t\tpgDBName = \"ginexamples\"\n\t}\n\n\tlogFile, ok := os.LookupEnv(\"LOGFILE\")\n\tif !ok {\n\t\tlogFile = \"\"\n\t}\n\n\treturn Config{\n\t\tPort: port,\n\t\tEnv: env,\n\t\tPGHost: pgHost,\n\t\tPGPort: pgPort,\n\t\tPGUser: pgUser,\n\t\tPGPassword: pgPassword,\n\t\tPGDBName: pgDBName,\n\t\tLogFile: logFile,\n\t}\n}", "func getConfig() (Config, error) {\n\tvar configPath string\n\tvar err error\n\n\tif !configRead {\n\t\tconfigPath, err = getConfigPath()\n\t\tif err != nil {\n\t\t\treturn Config{}, err\n\t\t}\n\t\tconfig, err = parseConfig(configPath)\n\t\tif err != nil {\n\t\t\treturn Config{}, err\n\t\t}\n\t\tconfigRead = true\n\t}\n\n\treturn config, nil\n}", "func GetConfig(key string) string {\n\tconfig := make(map[string]string)\n\tb, err := ioutil.ReadFile(\"config.json\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tjson.Unmarshal(b, &config)\n\treturn config[key]\n}", "func (rm *ResourceManager) GetConfig(name string) *interface{} {\n\tif i, ok := rm.configuration[name]; ok {\n\t\treturn &i\n\t}\n\treturn nil\n}", "func getConfig(filename string) Config {\n\tvar conf Config\n\tif _, err := toml.DecodeFile(filename, &conf); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Set the defaults\n\tfor _, output := range conf.Outputs {\n\t\toutput.Topic = conf.Mqtt.BaseTopic + output.Topic\n\t\tfor _, key := range output.Keys {\n\t\t\tif key.Name == \"\" {\n\t\t\t\tkey.Name = conf.DefaultKey\n\t\t\t}\n\t\t\tif key.UnitName == \"\" {\n\t\t\t\tkey.UnitName = conf.DefaultUnitKey\n\t\t\t}\n\t\t}\n\t}\n\treturn conf\n}", "func getConfig(c *gin.Context) {\n\tc.HTML(http.StatusOK, \"config_ui.html\", gin.H{\n\t\t\"config\": biConfig,\n\t})\n}", "func GetConfig() Config {\n\treturn cfg\n}", "func getConfig(configFileName string, configPointer interface{}) error {\r\n\tif fileExists(configFileName) { //Get existing configuration from configFileName\r\n\t\tb, err := ioutil.ReadFile(configFileName)\r\n\t\tif err != nil {\r\n\t\t\treturn errors.WithStack(err)\r\n\t\t}\r\n\r\n\t\terr = json.Unmarshal(b, configPointer)\r\n\t\tif err != nil {\r\n\t\t\t//fmt.Println(\"Failed to unmarshal configuration file\")\r\n\t\t\treturn errors.WithStack(err)\r\n\t\t}\r\n\r\n\t\treturn nil\r\n\t}\r\n\r\n\t//If configFileName doesn't exist, create a new config file\r\n\tb, err := json.MarshalIndent(configPointer, \"\", \" \")\r\n\tif err != nil {\r\n\t\t//fmt.Println(\"Failed to marshal configuration file\")\r\n\t\treturn errors.WithStack(err)\r\n\t}\r\n\r\n\terr = ioutil.WriteFile(configFileName, b, 0644)\r\n\tif err != nil {\r\n\t\t//fmt.Println(\"Failed to write configuration file\")\r\n\t\treturn errors.WithStack(err)\r\n\t}\r\n\r\n\treturn errors.New(\"Configuration file not set\")\r\n}" ]
[ "0.5595617", "0.55334187", "0.55258375", "0.5509629", "0.5492174", "0.54913056", "0.5481108", "0.5445968", "0.54088974", "0.53772765", "0.5319755", "0.5253507", "0.5245969", "0.5245487", "0.5240613", "0.522218", "0.5200091", "0.520003", "0.51966673", "0.5176976", "0.51648146", "0.5161643", "0.51595664", "0.51576674", "0.5156844", "0.51515514", "0.5142542", "0.51382786", "0.5122623", "0.5121728", "0.5118902", "0.51183575", "0.5113999", "0.51115537", "0.5109747", "0.510082", "0.50886303", "0.50878024", "0.5057569", "0.5056976", "0.50549823", "0.50535953", "0.5051532", "0.5050053", "0.50448585", "0.50434124", "0.5035839", "0.5035067", "0.5033942", "0.50336814", "0.50318897", "0.5029541", "0.5022644", "0.5013639", "0.5013568", "0.50131804", "0.5008003", "0.49967122", "0.49906662", "0.49830148", "0.49779916", "0.49771395", "0.49561882", "0.49557394", "0.4951337", "0.4950067", "0.49491987", "0.49423146", "0.4924836", "0.49198624", "0.49182624", "0.4917293", "0.49080154", "0.4898309", "0.48974055", "0.48974055", "0.48911768", "0.4888696", "0.48800442", "0.4879944", "0.48791608", "0.48789874", "0.4877421", "0.48756948", "0.4872039", "0.48704287", "0.48696694", "0.48692694", "0.48686647", "0.48614076", "0.4860744", "0.48589122", "0.48543647", "0.48537153", "0.48518372", "0.48489326", "0.48418036", "0.48396", "0.4836377", "0.48345575" ]
0.776008
0
NewMockProviders creates a new mock instance
NewMockProviders создает новый экземпляр мока
func NewMockProviders(ctrl *gomock.Controller) *MockProviders { mock := &MockProviders{ctrl: ctrl} mock.recorder = &MockProvidersMockRecorder{mock} return mock }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "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 NewProviders() *Providers {\n\treturn &Providers{\n\t\tinternal: provider.Unknown,\n\t\tproviders: map[string]Provider{},\n\t}\n}", "func NewEventProviderMock(t NewEventProviderMockT) *EventProviderMock {\n\tmock := &EventProviderMock{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\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 NewMock(t *testing.T) *MockT { return &MockT{t: t} }", "func NewMockProvider(ctrl *gomock.Controller) *MockProvider {\n\tmock := &MockProvider{ctrl: ctrl}\n\tmock.recorder = &MockProviderMockRecorder{mock}\n\treturn mock\n}", "func NewMockProvider(ctrl *gomock.Controller) *MockProvider {\n\tmock := &MockProvider{ctrl: ctrl}\n\tmock.recorder = &MockProviderMockRecorder{mock}\n\treturn mock\n}", "func NewMockProvider(ctrl *gomock.Controller) *MockProvider {\n\tmock := &MockProvider{ctrl: ctrl}\n\tmock.recorder = &MockProviderMockRecorder{mock}\n\treturn mock\n}", "func NewMockProvider(ctrl *gomock.Controller) *MockProvider {\n\tmock := &MockProvider{ctrl: ctrl}\n\tmock.recorder = &MockProviderMockRecorder{mock}\n\treturn mock\n}", "func NewMockProvider(ctrl *gomock.Controller) *MockProvider {\n\tmock := &MockProvider{ctrl: ctrl}\n\tmock.recorder = &MockProviderMockRecorder{mock}\n\treturn mock\n}", "func NewMockProvider(ctrl *gomock.Controller) *MockProvider {\n\tmock := &MockProvider{ctrl: ctrl}\n\tmock.recorder = &MockProviderMockRecorder{mock}\n\treturn mock\n}", "func NewMockProvider(ctrl *gomock.Controller) *MockProvider {\n\tmock := &MockProvider{ctrl: ctrl}\n\tmock.recorder = &MockProviderMockRecorder{mock}\n\treturn mock\n}", "func NewMockProvider(ctrl *gomock.Controller) *MockProvider {\n\tmock := &MockProvider{ctrl: ctrl}\n\tmock.recorder = &MockProviderMockRecorder{mock}\n\treturn mock\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 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 GetProviders(w http.ResponseWriter, r *http.Request) {\n\tencoder := json.NewEncoder(w)\n\n\tencoder.Encode(mock.Providers)\n}", "func newTestFabricProviderSet(providers ...string) *FabricProviderSet {\n\tset := new(FabricProviderSet)\n\tfor i, p := range providers {\n\t\tset.Add(&FabricProvider{\n\t\t\tName: p,\n\t\t\tPriority: i,\n\t\t})\n\t}\n\n\treturn set\n}", "func New() *Mock {\n\treturn &Mock{\n\t\tm: mockMap{},\n\t\toldTransport: http.DefaultTransport,\n\t}\n}", "func New(cfg *Config,\n\tapiManager apimanager.Provider,\n\tlogger logger.Logger, registerer prometheus.Registerer) (Provider, error) {\n\tservice := &MockServer{\n\t\tcfg: cfg,\n\t\tregisterer: registerer,\n\t\tapiManager: apiManager,\n\t\tLogger: logger.NewLogger(\"httpMockServer\"),\n\t}\n\treturn service, nil\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 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 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 newInMemoryProviders(c *StreamingV1alpha1Client, namespace string) *inMemoryProviders {\n\treturn &inMemoryProviders{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\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 newFakeTracerProviderStore() *fakeTracerProviderStore {\n\texps := []sdktrace.SpanExporter{}\n\treturn &fakeTracerProviderStore{exps, nil, nil}\n}", "func NewMock(now time.Time) *Mock {\n\treturn &Mock{\n\t\tnow: now,\n\t\tmockTimers: &timerHeap{},\n\t}\n}", "func newMockSubscriber() mockSubscriber {\n\treturn mockSubscriber{}\n}", "func New() provider.Provider {\n\tp := newProvider()\n\n\treturn p\n}", "func initProviders(ko *koanf.Koanf, lo *logrus.Logger, metrics *metrics.Manager) []prvs.Provider {\n\tprovs := make([]prvs.Provider, 0)\n\n\t// Loop over all providers listed in config.\n\tfor _, name := range ko.MapKeys(\"providers\") {\n\t\tcfgKey := fmt.Sprintf(\"providers.%s\", name)\n\t\tprovType := ko.String(fmt.Sprintf(\"%s.type\", cfgKey))\n\n\t\tswitch provType {\n\t\tcase \"google_chat\":\n\t\t\tgchat, err := google_chat.NewGoogleChat(\n\t\t\t\tgoogle_chat.GoogleChatOpts{\n\t\t\t\t\tLog: lo,\n\t\t\t\t\tTimeout: ko.MustDuration(fmt.Sprintf(\"%s.timeout\", cfgKey)),\n\t\t\t\t\tMaxIdleConn: ko.MustInt(fmt.Sprintf(\"%s.max_idle_conns\", cfgKey)),\n\t\t\t\t\tProxyURL: ko.String(fmt.Sprintf(\"%s.proxy_url\", cfgKey)),\n\t\t\t\t\tEndpoint: ko.MustString(fmt.Sprintf(\"%s.endpoint\", cfgKey)),\n\t\t\t\t\tRoom: name,\n\t\t\t\t\tTemplate: ko.MustString(fmt.Sprintf(\"%s.template\", cfgKey)),\n\t\t\t\t\tThreadTTL: ko.MustDuration(fmt.Sprintf(\"%s.thread_ttl\", cfgKey)),\n\t\t\t\t\tMetrics: metrics,\n\t\t\t\t\tDryRun: ko.Bool(fmt.Sprintf(\"%s.dry_run\", cfgKey)),\n\t\t\t\t},\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\tlo.WithError(err).Fatal(\"error initialising google chat provider\")\n\t\t\t}\n\n\t\t\tlo.WithField(\"room\", gchat.Room()).Info(\"initialised provider\")\n\t\t\tprovs = append(provs, gchat)\n\t\t}\n\t}\n\n\tif len(provs) == 0 {\n\t\tlo.Fatal(\"no providers listed in config\")\n\t}\n\n\treturn provs\n}", "func NewMock() *Mock {\n\treturn &Mock{VolumesMock: &VolumesServiceMock{}}\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 New() confmap.Provider {\n\treturn &provider{}\n}", "func newMockNetworks() (*MockNetwork, *MockNetwork) {\n\tc := mockCon.NewConn()\n\treturn &MockNetwork{c.Client}, &MockNetwork{c.Server}\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 NewProvider(t *testing.T) *Provider {\n\treturn &Provider{\n\t\tt: t,\n\t\tcounters: make(map[string]*Counter),\n\t\thistograms: make(map[string]*Histogram),\n\t\tgauges: make(map[string]*Gauge),\n\t\tcardCounters: make(map[string]*xmetrics.HLLCounter),\n\t}\n}", "func New() *Provider {\n\treturn &Provider{clients: make(map[string]ClientVersionProvider)}\n}", "func NewMockSupport() *MockSupport {\n\treturn &MockSupport{\n\t\tPublisher: NewBlockPublisher(),\n\t}\n}", "func NewMockHTTPProvider(ctrl *gomock.Controller) *MockHTTPProvider {\n\tmock := &MockHTTPProvider{ctrl: ctrl}\n\tmock.recorder = &MockHTTPProviderMockRecorder{mock}\n\treturn mock\n}", "func NewForge(t interface {\n\tmock.TestingT\n\tCleanup(func())\n}) *Forge {\n\tmock := &Forge{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func New(v interface{}) (provider.Provider, error) {\n\ts := Spec{}\n\treturn &s, ioutil.Intermarshal(v, &s)\n}", "func (m *MockNotifierProvider) New(arg0 upgraded.State, arg1 *cert.Info, arg2 config.Schema) upgraded.Notifier {\n\tret := m.ctrl.Call(m, \"New\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(upgraded.Notifier)\n\treturn ret0\n}", "func NewProvider(log logging.Logger) *Provider {\n\treturn &Provider{\n\t\tapi: &api{},\n\t\tlog: log,\n\t}\n}", "func NewProvider(params ...SDKContextParams) *Provider {\n\tctxProvider := Provider{}\n\tfor _, param := range params {\n\t\tparam(&ctxProvider)\n\t}\n\treturn &ctxProvider\n}", "func (m *MockWatcherConstructor) New(arg0 Machine, arg1 string, arg2 []string, arg3, arg4, arg5 string, arg6 time.Duration, arg7 map[string]interface{}) (interface{}, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"New\", arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7)\n\tret0, _ := ret[0].(interface{})\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func NewSQLMockProvider() (*SQLMockProvider, sqlmock.Sqlmock) {\n\tprovider := SQLMockProvider{\n\t\tSQLProvider{\n\t\t\tname: \"sqlmock\",\n\n\t\t\tsqlUpgradesCreateTableStatements: sqlUpgradeCreateTableStatements,\n\t\t\tsqlUpgradesCreateTableIndexesStatements: sqlUpgradesCreateTableIndexesStatements,\n\n\t\t\tsqlGetPreferencesByUsername: fmt.Sprintf(\"SELECT second_factor_method FROM %s WHERE username=?\", userPreferencesTableName),\n\t\t\tsqlUpsertSecondFactorPreference: fmt.Sprintf(\"REPLACE INTO %s (username, second_factor_method) VALUES (?, ?)\", userPreferencesTableName),\n\n\t\t\tsqlTestIdentityVerificationTokenExistence: fmt.Sprintf(\"SELECT EXISTS (SELECT * FROM %s WHERE token=?)\", identityVerificationTokensTableName),\n\t\t\tsqlInsertIdentityVerificationToken: fmt.Sprintf(\"INSERT INTO %s (token) VALUES (?)\", identityVerificationTokensTableName),\n\t\t\tsqlDeleteIdentityVerificationToken: fmt.Sprintf(\"DELETE FROM %s WHERE token=?\", identityVerificationTokensTableName),\n\n\t\t\tsqlGetTOTPSecretByUsername: fmt.Sprintf(\"SELECT secret FROM %s WHERE username=?\", totpSecretsTableName),\n\t\t\tsqlUpsertTOTPSecret: fmt.Sprintf(\"REPLACE INTO %s (username, secret) VALUES (?, ?)\", totpSecretsTableName),\n\t\t\tsqlDeleteTOTPSecret: fmt.Sprintf(\"DELETE FROM %s WHERE username=?\", totpSecretsTableName),\n\n\t\t\tsqlGetU2FDeviceHandleByUsername: fmt.Sprintf(\"SELECT keyHandle, publicKey FROM %s WHERE username=?\", u2fDeviceHandlesTableName),\n\t\t\tsqlUpsertU2FDeviceHandle: fmt.Sprintf(\"REPLACE INTO %s (username, keyHandle, publicKey) VALUES (?, ?, ?)\", u2fDeviceHandlesTableName),\n\n\t\t\tsqlInsertAuthenticationLog: fmt.Sprintf(\"INSERT INTO %s (username, successful, time) VALUES (?, ?, ?)\", authenticationLogsTableName),\n\t\t\tsqlGetLatestAuthenticationLogs: fmt.Sprintf(\"SELECT successful, time FROM %s WHERE time>? AND username=? ORDER BY time DESC\", authenticationLogsTableName),\n\n\t\t\tsqlGetExistingTables: \"SELECT name FROM sqlite_master WHERE type='table'\",\n\n\t\t\tsqlConfigSetValue: fmt.Sprintf(\"REPLACE INTO %s (category, key_name, value) VALUES (?, ?, ?)\", configTableName),\n\t\t\tsqlConfigGetValue: fmt.Sprintf(\"SELECT value FROM %s WHERE category=? AND key_name=?\", configTableName),\n\t\t},\n\t}\n\n\tdb, mock, err := sqlmock.New()\n\n\tif err != nil {\n\t\tprovider.log.Fatalf(\"Unable to create SQL database: %s\", err)\n\t}\n\n\tprovider.db = db\n\n\t/*\n\t\tWe do initialize in the tests rather than in the new up.\n\t*/\n\n\treturn &provider, mock\n}", "func NewTestProvider() *TestProvider {\n\treturn &TestProvider{make(map[string]Client)}\n}", "func NewMockDefault() *Mock {\n\tmgr := new(Mock)\n\tvar pluginsMap = make(map[string]managerContracts.Plugin)\n\tvar cwPlugin = managerContracts.Plugin{\n\t\tHandler: cloudwatch.NewMockDefault(),\n\t}\n\tpluginsMap[CloudWatchId] = cwPlugin\n\n\tmgr.On(\"GetRegisteredPlugins\").Return(pluginsMap)\n\tmgr.On(\"Name\").Return(CloudWatchId)\n\tmgr.On(\"Execute\", mock.AnythingOfType(\"context.T\")).Return(nil)\n\tmgr.On(\"RequestStop\", mock.AnythingOfType(\"string\")).Return(nil)\n\tmgr.On(\"StopPlugin\", mock.AnythingOfType(\"string\"), mock.Anything).Return(nil)\n\tmgr.On(\"StartPlugin\", mock.AnythingOfType(\"string\"), mock.AnythingOfType(\"string\"), mock.AnythingOfType(\"string\"), mock.AnythingOfType(\"task.CancelFlag\")).Return(nil)\n\treturn mgr\n}", "func NewMockProviderContext() *MockProviderContext {\n\tcontext := MockProviderContext{\n\t\tconfig: NewMockConfig(),\n\t\tsigningManager: NewMockSigningManager(),\n\t\tcryptoSuite: &MockCryptoSuite{},\n\t}\n\treturn &context\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 New(clientset *clusterinfo.OpenShift) (*Provider, error) {\n\treturn &Provider{\n\t\toc: clientset,\n\t}, nil\n}", "func NewForTesting() buckets.Provider {\n\treturn newWithOptions(option.WithoutAuthentication())\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 newStatsProvider(\n\tcadvisor cadvisor.Interface,\n\tpodManager PodManager,\n\truntimeCache kubecontainer.RuntimeCache,\n\tcontainerStatsProvider containerStatsProvider,\n) *Provider {\n\treturn &Provider{\n\t\tcadvisor: cadvisor,\n\t\tpodManager: podManager,\n\t\truntimeCache: runtimeCache,\n\t\tcontainerStatsProvider: containerStatsProvider,\n\t}\n}", "func NewProvider(api *API, vin string, cache time.Duration) *Provider {\n\timpl := &Provider{\n\t\tstatusG: provider.Cached(func() (RechargeStatus, error) {\n\t\t\treturn api.RechargeStatus(vin)\n\t\t}, cache),\n\t}\n\treturn impl\n}", "func NewProvider(respG func() (Response, error), cache time.Duration) *Provider {\n\treturn &Provider{\n\t\tapiG: provider.NewCached(func() (interface{}, error) {\n\t\t\treturn respG()\n\t\t}, cache).InterfaceGetter(),\n\t}\n}", "func NewProvider(api *API, vin string, cache time.Duration) *Provider {\n\timpl := &Provider{\n\t\tchargerG: provider.Cached(func() (ChargerResponse, error) {\n\t\t\treturn api.Charger(vin)\n\t\t}, cache),\n\t\tstatusG: provider.Cached(func() (StatusResponse, error) {\n\t\t\treturn api.Status(vin)\n\t\t}, cache),\n\t\tclimateG: provider.Cached(func() (ClimaterResponse, error) {\n\t\t\treturn api.Climater(vin)\n\t\t}, cache),\n\t\tpositionG: provider.Cached(func() (PositionResponse, error) {\n\t\t\treturn api.Position(vin)\n\t\t}, cache),\n\t\taction: func(action, value string) error {\n\t\t\treturn api.Action(vin, action, value)\n\t\t},\n\t\trr: func() (RolesRights, error) {\n\t\t\treturn api.RolesRights(vin)\n\t\t},\n\t}\n\treturn impl\n}", "func NewProvider(typeName string, crypto domain.Crypto) *Provider {\n\treturn &Provider{\n\t\ttypeName: typeName,\n\t\tbqClients: map[string]*bigQueryClient{},\n\t\tiamClients: map[string]*iamClient{},\n\t\tcrypto: crypto,\n\t}\n}", "func New(cfg *config.Config) *HsmProvidersService {\n\n\treturn &HsmProvidersService{Client: client.New(\n\t\t*cfg,\n\t\tmetadata.ClientInfo{\n\t\t\tServiceName: ServiceName,\n\t\t\tEndpoint: *cfg.Endpoint,\n\t\t\tAPIVersion: pingaccess.SDKVersion,\n\t\t},\n\t)}\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 NewProvider() *Provider {\n\treturn &Provider{}\n}", "func (m *MockAddonProvidersService) AddonProvidersList(arg0 context.Context) ([]*scalingo.AddonProvider, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AddonProvidersList\", arg0)\n\tret0, _ := ret[0].([]*scalingo.AddonProvider)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func Providers() []Provider {\n\tif MockProviders != nil {\n\t\treturn MockProviders\n\t}\n\tallProvidersMu.Lock()\n\tdefer allProvidersMu.Unlock()\n\treturn allProviders\n}", "func NewMock() Cache {\n\treturn &mock{}\n}", "func RegisterProviders(providerFuncs ...ProviderFunc) {\n\t_setupMux.Lock()\n\tdefer _setupMux.Unlock()\n\t_staticProviderFuncs = append(_staticProviderFuncs, providerFuncs...)\n}", "func NewProvider(expires time.Duration) *Provider {\n\treturn &Provider{list: list.New(), sessions: make(map[string]*list.Element, 0), databases: make([]Database, 0), Expires: expires}\n}", "func (m *MockProviderManager) CalculateNewProvider(arg0 string) (*resource.ResourceProvider, error) {\n\tret := m.ctrl.Call(m, \"CalculateNewProvider\", arg0)\n\tret0, _ := ret[0].(*resource.ResourceProvider)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func NewMockBootstrapperProvider(ctrl *gomock.Controller) *MockBootstrapperProvider {\n\tmock := &MockBootstrapperProvider{ctrl: ctrl}\n\tmock.recorder = &MockBootstrapperProviderMockRecorder{mock}\n\treturn mock\n}", "func NewMockReplacer(\n\tctx context.Context,\n\tregion string,\n\tprofile string) *Replacer {\n\n\tasgroup := newAsg(region, profile)\n\tdeploy := fsm.NewDeploy(\"start\")\n\tasgroup.Ec2Api = &mockEC2iface{}\n\tasgroup.AsgAPI = &mockASGiface{}\n\tasgroup.EcsAPI = &mockECSiface{}\n\treturn &Replacer{\n\t\tctx: ctx,\n\t\tasg: asgroup,\n\t\tdeploy: deploy,\n\t}\n}", "func New(config *Config) (*Provider, error) {\n\tif config.URL == \"\" {\n\t\tconfig.URL = fmt.Sprintf(\"http://%s\", config.ListenAddr)\n\t}\n\n\tif config.TOTP == \"\" {\n\t\tkey, err := totp.Generate(totp.GenerateOpts{\n\t\t\tIssuer: \"karmabot\",\n\t\t\tAccountName: \"slack\",\n\t\t})\n\n\t\tif err != nil {\n\t\t\tconfig.Log.Err(err).Fatal(\"an error occurred while generating a TOTP key\")\n\t\t} else {\n\t\t\tconfig.Log.KV(\"totpKey\", key.Secret()).Fatal(\"please use the following TOTP key\")\n\t\t}\n\t}\n\n\tprovider := &Provider{\n\t\tConfig: config,\n\t\tui: newUI(config),\n\t}\n\n\treturn provider, nil\n}", "func NewProvider() *Provider {\n\treturn &Provider{\n\t\tconfig: new(Config),\n\t\tmemoryDB: new(session.Dict),\n\t\texpiration: 0,\n\n\t\tstorePool: sync.Pool{\n\t\t\tNew: func() interface{} {\n\t\t\t\treturn new(Store)\n\t\t\t},\n\t\t},\n\t}\n}", "func NewMock() *Mock {\n\treturn &Mock{now: time.Unix(0, 0)}\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 NewMockChoriaProvider(ctrl *gomock.Controller) *MockChoriaProvider {\n\tmock := &MockChoriaProvider{ctrl: ctrl}\n\tmock.recorder = &MockChoriaProviderMockRecorder{mock}\n\treturn mock\n}", "func NewProvider(logger *zap.Logger) Provider {\n\treturn newProvider(logger)\n}", "func New(provider string, p *ProviderData) Provider {\n\tswitch provider {\n\tcase \"myusa\":\n\t\treturn NewMyUsaProvider(p)\n\tcase \"linkedin\":\n\t\treturn NewLinkedInProvider(p)\n\tcase \"facebook\":\n\t\treturn NewFacebookProvider(p)\n\tcase \"github\":\n\t\treturn NewGitHubProvider(p)\n\tcase \"azure\":\n\t\treturn NewAzureProvider(p)\n\tcase \"gitlab\":\n\t\treturn NewGitLabProvider(p)\n\tdefault:\n\t\treturn NewGoogleProvider(p)\n\t}\n}", "func NewValidatorProvider(t mockConstructorTestingTNewValidatorProvider) *ValidatorProvider {\n\tmock := &ValidatorProvider{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\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 New(clientset *clusterinfo.OpenShift, infraStatus *config.InfrastructureStatus) *Provider {\n\treturn &Provider{\n\t\toc: clientset,\n\t\tInfrastructureStatus: infraStatus,\n\t}\n}", "func ToMockProvider(p goth.Provider) *MockProvider {\n\treturn p.(*MockProvider)\n}", "func newMockTransport() *mockTransport {\n\treturn &mockTransport{\n\t\turlToResponseAndError: make(map[string]mockTransportResponse),\n\t\trequestURLsReceived: make([]string, 0),\n\t}\n}", "func NewProvider(log *zap.Logger, url, clusterID, clientID string) mq.Provider {\n\tif len(clusterID) == 0 || len(clientID) == 0 {\n\t\treturn nil\n\t}\n\n\tcfg := newConfig(url, clusterID, clientID)\n\n\tif log == nil {\n\t\tlog = zap.NewNop()\n\t}\n\n\treturn &provider{\n\t\tconfig: cfg,\n\t\tconsumer: newConsumer(log, url, clusterID, clientID),\n\t\tlog: log,\n\t}\n}", "func NewMockMiddlewares(ctrl *gomock.Controller) *MockMiddlewares {\n\tmock := &MockMiddlewares{ctrl: ctrl}\n\tmock.recorder = &MockMiddlewaresMockRecorder{mock}\n\treturn mock\n}", "func NewMockDiscoveryProvider(err error, peers []fab.Peer) (*MockStaticDiscoveryProvider, error) {\n\treturn &MockStaticDiscoveryProvider{Error: err, Peers: peers}, nil\n}", "func NewMockObject(uid, name, ns string, res api.Resource) api.Object {\n\treturn NewObject(uuid.NewFromString(uid), name, ns, res)\n}", "func (t TestFactoryT) NewMockMemStore() *memStoreImpl {\n\tmetaStore := new(metaMocks.MetaStore)\n\tdiskStore := new(diskMocks.DiskStore)\n\tredoLogManagerMaster, _ := redolog.NewRedoLogManagerMaster(&common.RedoLogConfig{}, diskStore, metaStore)\n\tbootstrapToken := new(memComMocks.BootStrapToken)\n\tbootstrapToken.On(\"AcquireToken\", mock.Anything, mock.Anything).Return(true)\n\tbootstrapToken.On(\"ReleaseToken\", mock.Anything, mock.Anything).Return()\n\n\treturn NewMemStore(metaStore, diskStore, NewOptions(bootstrapToken, redoLogManagerMaster)).(*memStoreImpl)\n}", "func NewMock() *MockMetrics {\n\treturn &MockMetrics{}\n}", "func NewProvider(logger *zap.Logger, options ...ProviderOption) Provider {\n\treturn newProvider(logger, options...)\n}", "func New(t *testing.T, requests []ExpectedRequest) *httptest.Server {\n\th := mockHandler(t, requests)\n\treturn httptest.NewServer(h)\n}", "func New(t *testing.T, requests []ExpectedRequest) *httptest.Server {\n\th := mockHandler(t, requests)\n\treturn httptest.NewServer(h)\n}", "func New(c *Config) *Provider {\n\treturn &Provider{\n\t\tConfig: c,\n\t}\n}", "func createProviders(tmpFiles *tmpCredsFiles) (certprovider.Provider, certprovider.Provider, certprovider.Provider, certprovider.Provider, error) {\n\tclientIdentityOptions := pemfile.Options{\n\t\tCertFile: tmpFiles.clientCertTmp.Name(),\n\t\tKeyFile: tmpFiles.clientKeyTmp.Name(),\n\t\tRefreshDuration: credRefreshingInterval,\n\t}\n\tclientIdentityProvider, err := pemfile.NewProvider(clientIdentityOptions)\n\tif err != nil {\n\t\treturn nil, nil, nil, nil, err\n\t}\n\tclientRootOptions := pemfile.Options{\n\t\tRootFile: tmpFiles.clientTrustTmp.Name(),\n\t\tRefreshDuration: credRefreshingInterval,\n\t}\n\tclientRootProvider, err := pemfile.NewProvider(clientRootOptions)\n\tif err != nil {\n\t\treturn nil, nil, nil, nil, err\n\t}\n\tserverIdentityOptions := pemfile.Options{\n\t\tCertFile: tmpFiles.serverCertTmp.Name(),\n\t\tKeyFile: tmpFiles.serverKeyTmp.Name(),\n\t\tRefreshDuration: credRefreshingInterval,\n\t}\n\tserverIdentityProvider, err := pemfile.NewProvider(serverIdentityOptions)\n\tif err != nil {\n\t\treturn nil, nil, nil, nil, err\n\t}\n\tserverRootOptions := pemfile.Options{\n\t\tRootFile: tmpFiles.serverTrustTmp.Name(),\n\t\tRefreshDuration: credRefreshingInterval,\n\t}\n\tserverRootProvider, err := pemfile.NewProvider(serverRootOptions)\n\tif err != nil {\n\t\treturn nil, nil, nil, nil, err\n\t}\n\treturn clientIdentityProvider, clientRootProvider, serverIdentityProvider, serverRootProvider, nil\n}", "func (t TestFactoryT) NewMockMemStore() *memStoreImpl {\n\tmetaStore := new(metaMocks.MetaStore)\n\tdiskStore := new(diskMocks.DiskStore)\n\tredoLogManagerMaster, _ := redolog.NewRedoLogManagerMaster(\"\", &common.RedoLogConfig{}, diskStore, metaStore)\n\tbootstrapToken := new(memComMocks.BootStrapToken)\n\tbootstrapToken.On(\"AcquireToken\", mock.Anything, mock.Anything).Return(true)\n\tbootstrapToken.On(\"ReleaseToken\", mock.Anything, mock.Anything).Return()\n\n\treturn NewMemStore(metaStore, diskStore, NewOptions(bootstrapToken, redoLogManagerMaster)).(*memStoreImpl)\n}", "func New() buckets.Provider {\n\treturn newWithOptions()\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 providerFactory(meta *providercache.CachedProvider) providers.Factory {\n\treturn func() (providers.Interface, error) {\n\t\texecFile, err := meta.ExecutableFile()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tconfig := &plugin.ClientConfig{\n\t\t\tHandshakeConfig: tfplugin.Handshake,\n\t\t\tLogger: logging.NewProviderLogger(\"\"),\n\t\t\tAllowedProtocols: []plugin.Protocol{plugin.ProtocolGRPC},\n\t\t\tManaged: true,\n\t\t\tCmd: exec.Command(execFile),\n\t\t\tAutoMTLS: enableProviderAutoMTLS,\n\t\t\tVersionedPlugins: tfplugin.VersionedPlugins,\n\t\t\tSyncStdout: logging.PluginOutputMonitor(fmt.Sprintf(\"%s:stdout\", meta.Provider)),\n\t\t\tSyncStderr: logging.PluginOutputMonitor(fmt.Sprintf(\"%s:stderr\", meta.Provider)),\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 5:\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\tpanic(\"unsupported protocol version\")\n\t\t}\n\t}\n}", "func init() {\n\tglobalContext = TestContext()\n\tfor name, descriptor := range providers {\n\t\tglobalContext.RegisterProvider(name, descriptor)\n\t}\n}", "func newPluginProvider(pluginBinDir string, provider kubeletconfig.CredentialProvider) (*pluginProvider, error) {\n\tmediaType := \"application/json\"\n\tinfo, ok := runtime.SerializerInfoForMediaType(codecs.SupportedMediaTypes(), mediaType)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"unsupported media type %q\", mediaType)\n\t}\n\n\tgv, ok := apiVersions[provider.APIVersion]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"invalid apiVersion: %q\", provider.APIVersion)\n\t}\n\n\tclock := clock.RealClock{}\n\n\treturn &pluginProvider{\n\t\tclock: clock,\n\t\tmatchImages: provider.MatchImages,\n\t\tcache: cache.NewExpirationStore(cacheKeyFunc, &cacheExpirationPolicy{clock: clock}),\n\t\tdefaultCacheDuration: provider.DefaultCacheDuration.Duration,\n\t\tlastCachePurge: clock.Now(),\n\t\tplugin: &execPlugin{\n\t\t\tname: provider.Name,\n\t\t\tapiVersion: provider.APIVersion,\n\t\t\tencoder: codecs.EncoderForVersion(info.Serializer, gv),\n\t\t\tpluginBinDir: pluginBinDir,\n\t\t\targs: provider.Args,\n\t\t\tenvVars: provider.Env,\n\t\t\tenviron: os.Environ,\n\t\t},\n\t}, nil\n}", "func newMock(deps mockDependencies, t testing.TB) (Component, error) {\n\tbackupConfig := config.NewConfig(\"\", \"\", strings.NewReplacer())\n\tbackupConfig.CopyConfig(config.Datadog)\n\n\tconfig.Datadog.CopyConfig(config.NewConfig(\"mock\", \"XXXX\", strings.NewReplacer()))\n\n\tconfig.SetFeatures(t, deps.Params.Features...)\n\n\t// call InitConfig to set defaults.\n\tconfig.InitConfig(config.Datadog)\n\tc := &cfg{\n\t\tConfig: config.Datadog,\n\t}\n\n\tif !deps.Params.SetupConfig {\n\n\t\tif deps.Params.ConfFilePath != \"\" {\n\t\t\tconfig.Datadog.SetConfigType(\"yaml\")\n\t\t\terr := config.Datadog.ReadConfig(strings.NewReader(deps.Params.ConfFilePath))\n\t\t\tif err != nil {\n\t\t\t\t// The YAML was invalid, fail initialization of the mock config.\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t} else {\n\t\twarnings, _ := setupConfig(deps)\n\t\tc.warnings = warnings\n\t}\n\n\t// Overrides are explicit and will take precedence over any other\n\t// setting\n\tfor k, v := range deps.Params.Overrides {\n\t\tconfig.Datadog.Set(k, v)\n\t}\n\n\t// swap the existing config back at the end of the test.\n\tt.Cleanup(func() { config.Datadog.CopyConfig(backupConfig) })\n\n\treturn c, nil\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 New(t T) *Tester {\n\ttt := &Tester{\n\t\tt: t,\n\n\t\tclients: make(map[string]*client),\n\n\t\tcodecs: make(map[string]goka.Codec),\n\t\ttopicQueues: make(map[string]*queue),\n\t\tstorages: make(map[string]storage.Storage),\n\t}\n\ttt.tmgr = NewMockTopicManager(tt, 1, 1)\n\ttt.producer = newProducerMock(tt.handleEmit)\n\n\treturn tt\n}" ]
[ "0.6564672", "0.6390504", "0.63529956", "0.62278885", "0.61835265", "0.6167602", "0.6167602", "0.6167602", "0.6167602", "0.6167602", "0.6167602", "0.6167602", "0.6167602", "0.61669147", "0.6132294", "0.60496056", "0.5984718", "0.59554595", "0.59195", "0.59074426", "0.5889402", "0.587887", "0.5849598", "0.58472836", "0.5837561", "0.5832616", "0.5830016", "0.5820673", "0.5814565", "0.5805349", "0.57693017", "0.57537246", "0.57181144", "0.5709279", "0.5707897", "0.57027274", "0.5699361", "0.5677092", "0.5671614", "0.5654188", "0.5652066", "0.56485367", "0.5638125", "0.56343234", "0.5610135", "0.5605013", "0.56035286", "0.56015146", "0.55960894", "0.55893457", "0.55811256", "0.5563473", "0.5552943", "0.55477726", "0.5545581", "0.553752", "0.5532278", "0.553115", "0.5525606", "0.5525533", "0.55136824", "0.55109805", "0.55041796", "0.54930353", "0.5488427", "0.5482902", "0.54763305", "0.54746425", "0.54716176", "0.54572594", "0.54546005", "0.5449581", "0.54125273", "0.541115", "0.5405129", "0.54048425", "0.5403262", "0.54017735", "0.5400563", "0.5398795", "0.5383267", "0.53816384", "0.5380488", "0.5378469", "0.5377692", "0.53686434", "0.5365781", "0.53642213", "0.53642213", "0.5352168", "0.5337998", "0.5336663", "0.53365695", "0.53327274", "0.53267187", "0.5319543", "0.52884823", "0.5282567", "0.52784127", "0.52742845" ]
0.7244181
0
ChannelProvider mocks base method
ChannelProvider имитирует базовый метод
func (m *MockProviders) 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 *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 (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.74381363", "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.72489923
1
EndpointConfig mocks base method
EndpointConfig подделывает базовый метод
func (m *MockProviders) 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 *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 *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.7284712", "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.7244226
1
EndpointConfig indicates an expected call of EndpointConfig
EndpointConfig указывает на ожидаемый вызов 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
LocalDiscoveryProvider mocks base method
LocalDiscoveryProvider подделывает базовый метод
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
SigningManager indicates an expected call of SigningManager
SigningManager указывает на ожидаемый вызов 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
UserStore подделывает базовый метод
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
ChannelProvider mocks base method
ChannelProvider подделывает базовый метод
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
ChannelProvider указывает на ожидаемый вызов 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
EndpointConfig mocks base method
EndpointConfig имитирует базовый метод
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
EndpointConfig указывает на ожидаемый вызов 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
EnrollmentCertificate имитирует базовый метод
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
LocalDiscoveryProvider mocks base method
LocalDiscoveryProvider мокирует базовый метод
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
LocalDiscoveryProvider указывает на ожидаемый вызов 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
Мокирование базового метода PrivateKey
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
PrivateKey указывает на ожидаемый вызов 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
PublicVersion имитирует базовый метод
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
PublicVersion указывает на ожидаемый вызов 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 indicates an expected call of Serialize
Serialize указывает на ожидаемый вызов 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
Сигнатура указывает на ожидаемый вызов 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 indicates an expected call of SigningManager
SigningManager указывает на ожидаемый вызов 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
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.
Базовый аккаунт с поэтапным распределением Новый BaseVestingAccount создает новый объект BaseVestingAccount. Ответственность за обеспечение базового аккаунта достаточным количеством средств, соответствующим первоначальному объему поэтапного распределения, возлагается на вызывающего.
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.
LockedCoinsFromVesting возвращает все монеты, которые не могут быть потрачены (то есть заблокированы) для учетной записи с премией, учитывая текущие монеты с премией. Если монет не заблокировано, возвращается пустой срез монет. CONTRACT: Депонированные монеты с премией и vestingCoins должны быть отсортированы.
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.
TrackDelegation отслеживает объем делегирования для любого заданного типа учетной записи с учетом текущего объема монет, находящихся в процессе распределения, и текущего баланса учетной записи по видам делегированных монет. ДОГОВОР: Монеты учетной записи, делегированные монеты, монеты с распределением и делегированные монеты с распределением должны быть отсортированы.
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.
TrackUndelegation отслеживает объем неделегации, устанавливая необходимые значения, при которых делегированная премия и делегированная премия должны уменьшаться, а основные монеты должны увеличиваться. ЗАМЕЧАНИЕ: объем неделегации (возврат депозита) может превышать объем делегированной премии (депозита) из-за способа, которым неделегация обрезает возврат депозита, что может немного увеличить обменный курс валидатора (токены/акции), если неделегированные токены не являются целыми. ДОГОВОР: монеты аккаунта и монеты неделегации должны быть отсортированы.
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
GetOriginalVesting возвращает исходную сумму выплаты для учетной записи с пропорциональным распределением
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.
GetDelegatedFree возвращает объем делегирования учетной записи с линковкой, который не подлежит раскрытию.
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.
GetDelegatedVesting возвращает объем делегации учетной записи с привязкой, который еще не раскрылся.
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
GetEndTime возвращает конечное время востребования кошелька
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
MarshalYAML returns the YAML representation of a BaseVestingAccount.
MarshalYAML возвращает представление YAML 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
NewContinuousVestingAccountRaw создает новый объект ContinuousVestingAccount из 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
NewContinuousVestingAccount возвращает новый 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
GetStartTime returns the time when vesting starts for a continuous vesting account.
GetStartTime возвращает время, когда начнется распределение для аккаунта с непрерывным распределением.
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
MarshalYAML returns the YAML representation of a ContinuousVestingAccount.
MarshalYAML возвращает представление YAML 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
NewPeriodicVestingAccountRaw создает новый объект PeriodicVestingAccount из 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
NewPeriodicVestingAccount возвращает новый 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.
GetVestedCoins возвращает общее количество привилегированных монет. Если монет нет, возвращается nil.
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
LockedCoins returns the set of coins that are not spendable (i.e. locked), defined as the vesting coins that are not delegated.
LockedCoins возвращает набор монет, которые не могут быть потрачены (то есть заблокированы), определенные как вестинг-монеты, которые не делегированы.
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
GetStartTime returns the time when vesting starts for a periodic vesting account.
GetStartTime возвращает время, когда начнется начисление для аккаунта с периодическим начислением.
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.
GetVestingPeriods возвращает периоды vests, связанные с аккаунтом периодического vests.
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
MarshalYAML returns the YAML representation of a PeriodicVestingAccount.
MarshalYAML возвращает представление PeriodicVestingAccount в формате YAML.
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
NewPeriodicGrantAction возвращает AddGrantAction для 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.
AddToAccount реализует интерфейс exported.AddGrantAction. Он проверяет, является ли rawAccount объектом PeriodicVestingAccount, а затем добавляет описанный премьерный фонд этому объекту.
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.
AddGrant реализует интерфейс exported.GrantAccount.
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.
addGrant объединяет новый периодический премиальный грант с существующим 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
NewDelayedVestingAccountRaw создает новый объект DelayedVestingAccount из 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
NewDelayedVestingAccount возвращает 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.
GetVestedCoins возвращает общее количество застывших монет для аккаунта с отложенным распределением. Все монеты становятся застывшими только после завершения расписания.
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.
GetVestingCoins возвращает общее количество вesting-монет для задержанного вesting-счета.
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.
LockedCoins возвращает набор монет, которые не могут быть потрачены (то есть заблокированы), определенные как вesting монеты, которые не делегированы.
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.
TrackDelegation отслеживает желаемую сумму делегирования, устанавливая соответствующие значения для количества делегированных привилегированных монет, делегированных свободных монет и уменьшая общее количество базовых монет.
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.
GetStartTime возвращает ноль, так как учетная запись с отсрочкой выплат не имеет времени начала.
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
NewPermanentLockedAccount returns a PermanentLockedAccount
NewPermanentLockedAccount возвращает 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.
GetVestedCoins возвращает общее количество застекленных монет для аккаунта с постоянным блокированным расписанием. Все монеты становятся застекленными только после окончания расписания.
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.
GetVestingCoins возвращает общее количество привязанных монет для аккаунта с постоянной привязкой.
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
GetStartTime returns zero since a permanent locked vesting account has no start time.
GetStartTime возвращает ноль, так как аккаунт с постоянным заблокированным вesting имеет нет start time.
func (plva PermanentLockedAccount) GetStartTime() int64 { return 0 }
{ "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 (pva PeriodicVestingAccount) GetStartTime() int64 {\n\treturn pva.StartTime\n}", "func GetStartTime() time.Time {\n\treturn startAtTime\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 *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 (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 (req *StartWFSRequest) GetStartTime() time.Time {\n\treturn req.StartTime\n}", "func (txn TxnProbe) GetStartTime() time.Time {\n\treturn txn.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 (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 StartTime() time.Time {\n\treturn processStartTime\n}", "func (s *Session) GetStartTime() time.Time {\n\treturn s.started\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 (c *Container) GetStartTime() time.Time {\n\treturn c.start\n}", "func (c *Context) StartTime() *time.Time {\n\treturn &c.startTime\n}", "func (s *Storage) StartTime() (int64, error) {\n\treturn int64(model.Latest), nil\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 (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 (b *fixedResolutionValues) StartTime() xtime.UnixNano {\n\treturn b.startTime\n}", "func (f *Filler) StartTime() time.Time {\n\treturn f.tp\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 BeanstalkScheduledTaskOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BeanstalkScheduledTask) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o ElastigroupScheduledTaskOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ElastigroupScheduledTask) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o ReservedInstanceOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ReservedInstance) pulumi.StringOutput { return v.StartTime }).(pulumi.StringOutput)\n}", "func (req *ServerHTTPRequest) StartTime() time.Time {\n\treturn req.startTime\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 (r *ScheduledAction) StartTime() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"startTime\"])\n}", "func (p *SASQueryParameters) StartTime() time.Time {\n\treturn p.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 (instance *Instance) StartTime() time.Time {\n\tuptimeDuration := time.Duration(instance.Uptime) * time.Second\n\n\treturn time.Now().Add(-uptimeDuration)\n}", "func (o GoogleCloudRetailV2alphaConditionTimeRangeOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaConditionTimeRange) *string { return v.StartTime }).(pulumi.StringPtrOutput)\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 (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 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 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 (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 InstanceMaintenanceWindowOutput) StartTime() InstanceMaintenanceWindowStartTimeOutput {\n\treturn o.ApplyT(func(v InstanceMaintenanceWindow) InstanceMaintenanceWindowStartTime { return v.StartTime }).(InstanceMaintenanceWindowStartTimeOutput)\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 *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 (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 NodeGroupMaintenanceWindowOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v NodeGroupMaintenanceWindow) *string { return v.StartTime }).(pulumi.StringPtrOutput)\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 ResourcePolicyDailyCycleOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ResourcePolicyDailyCycle) *string { return v.StartTime }).(pulumi.StringPtrOutput)\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 (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 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 JobStatusPtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v JobStatus) *string { return v.StartTime }).(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 *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 (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 TimelineOutput) StartTime() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *Timeline) pulumi.IntPtrOutput { return v.StartTime }).(pulumi.IntPtrOutput)\n}", "func (e *Event) StartTime() Time {\n\treturn e.start\n}", "func (c deploymentChecker) BeginTime() uint64 {\n\treturn c.deployment.StartTime\n}", "func (o KubernetesClusterMaintenanceWindowNodeOsOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v KubernetesClusterMaintenanceWindowNodeOs) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o *V0037JobProperties) GetBeginTime() int64 {\n\tif o == nil || o.BeginTime == nil {\n\t\tvar ret int64\n\t\treturn ret\n\t}\n\treturn *o.BeginTime\n}", "func (o JobStatusOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v JobStatus) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o KubernetesClusterMaintenanceWindowNodeOsPtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *KubernetesClusterMaintenanceWindowNodeOs) *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 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 StartTime() {\n\tstart = time.Now()\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 (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 (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 InstanceMaintenanceWindowPtrOutput) StartTime() InstanceMaintenanceWindowStartTimePtrOutput {\n\treturn o.ApplyT(func(v *InstanceMaintenanceWindow) *InstanceMaintenanceWindowStartTime {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.StartTime\n\t}).(InstanceMaintenanceWindowStartTimePtrOutput)\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 *MobileAppInstallTimeSettings) GetStartDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n return m.startDateTime\n}", "func (o ResourcePolicyInstanceSchedulePolicyOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ResourcePolicyInstanceSchedulePolicy) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (f FakeContainerImpl) GetContainerStartTime(containerID string) (int64, error) {\n\tpanic(\"implement me\")\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 (_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 (m *GetSchedulePostRequestBody) GetStartTime()(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.DateTimeTimeZoneable) {\n return m.startTime\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 (o ResourcePolicyHourlyCycleOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ResourcePolicyHourlyCycle) *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 ResourcePolicyWeeklyCycleDayOfWeekOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ResourcePolicyWeeklyCycleDayOfWeek) *string { return v.StartTime }).(pulumi.StringPtrOutput)\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 (o *V0037Node) GetSlurmdStartTime() int64 {\n\tif o == nil || o.SlurmdStartTime == nil {\n\t\tvar ret int64\n\t\treturn ret\n\t}\n\treturn *o.SlurmdStartTime\n}", "func (o DataTransferConfigScheduleOptionsOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v DataTransferConfigScheduleOptions) *string { return v.StartTime }).(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 TriggerBuildArtifactsObjectsTimingOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v TriggerBuildArtifactsObjectsTiming) *string { return v.StartTime }).(pulumi.StringPtrOutput)\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 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 *OnpremUpgradePhase) 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 KubernetesClusterMaintenanceWindowAutoUpgradeOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v KubernetesClusterMaintenanceWindowAutoUpgrade) *string { return v.StartTime }).(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 (m *ConsensusCreateTopicTransactionBody) GetValidStartTime() *Timestamp {\n\tif m != nil {\n\t\treturn m.ValidStartTime\n\t}\n\treturn nil\n}", "func (m *ScheduleItem) GetStart()(DateTimeTimeZoneable) {\n val, err := m.GetBackingStore().Get(\"start\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(DateTimeTimeZoneable)\n }\n return nil\n}", "func (o StorageCapacityUnitOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *StorageCapacityUnit) pulumi.StringOutput { return v.StartTime }).(pulumi.StringOutput)\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 (o LookupJobResultOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupJobResult) string { return v.StartTime }).(pulumi.StringOutput)\n}", "func (o GoogleCloudRetailV2alphaConditionTimeRangeResponseOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaConditionTimeRangeResponse) string { return v.StartTime }).(pulumi.StringOutput)\n}" ]
[ "0.7989411", "0.77213776", "0.76390874", "0.7605982", "0.7384329", "0.7244314", "0.7236585", "0.7189344", "0.7175738", "0.7171928", "0.7160729", "0.7008172", "0.69832927", "0.6975663", "0.69752145", "0.695411", "0.69208306", "0.69165504", "0.6912835", "0.6835436", "0.6752777", "0.674334", "0.6660799", "0.66240734", "0.6618245", "0.6609172", "0.65879023", "0.6564642", "0.65571576", "0.6550238", "0.65228206", "0.65165055", "0.6487178", "0.6480315", "0.6458943", "0.6444386", "0.6424687", "0.64105546", "0.63850945", "0.63828355", "0.63828355", "0.6378862", "0.6359045", "0.6358781", "0.63544", "0.63504595", "0.6346177", "0.6345532", "0.6321708", "0.6295484", "0.6290065", "0.62897956", "0.62895054", "0.62895054", "0.6285061", "0.6281697", "0.6281697", "0.6267686", "0.62592524", "0.62577856", "0.62298524", "0.62197995", "0.62167805", "0.6216607", "0.6214464", "0.6212108", "0.62029207", "0.620115", "0.6198276", "0.6194738", "0.6190612", "0.61903775", "0.6179178", "0.617738", "0.61762244", "0.6167397", "0.6164916", "0.6164916", "0.6164526", "0.6154609", "0.61496806", "0.6147744", "0.61449105", "0.61411875", "0.6132521", "0.61237484", "0.61151797", "0.6104198", "0.6097349", "0.60873246", "0.60868675", "0.6074564", "0.6074094", "0.6071315", "0.60689956", "0.60677975", "0.6058576", "0.6057506", "0.60528153", "0.6050462" ]
0.82880247
0
GetEndTime returns a vesting account's end time, we return 0 to denote that a permanently locked vesting account has no end time.
GetEndTime возвращает конечное время учетной записи с привязкой, мы возвращаем 0, чтобы указать, что учетная запись с постоянной блокировкой не имеет конечного времени.
func (plva PermanentLockedAccount) GetEndTime() int64 { return 0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (bva BaseVestingAccount) GetEndTime() int64 {\n\treturn bva.EndTime\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 *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 (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 *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 (c *Container) GetEndTime() time.Time {\n\treturn c.end\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 (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 (_Casper *CasperSession) EndTime() (*big.Int, error) {\n\treturn _Casper.Contract.EndTime(&_Casper.CallOpts)\n}", "func (req *StartWFSRequest) GetEndTime() time.Time {\n\treturn req.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 (v *Validator) EndTime() time.Time {\n\treturn time.Unix(int64(v.End), 0)\n}", "func (_Casper *CasperCallerSession) EndTime() (*big.Int, error) {\n\treturn _Casper.Contract.EndTime(&_Casper.CallOpts)\n}", "func (m *GetSchedulePostRequestBody) GetEndTime()(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.DateTimeTimeZoneable) {\n return m.endTime\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 (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 (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 *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 *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 *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 (c deploymentChecker) EndTime() uint64 {\n\treturn c.deployment.ExpireTime\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 *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 (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 (_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 (r *ScheduledAction) EndTime() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"endTime\"])\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 (o *ApplianceSetupInfoAllOf) SetEndTime(v time.Time) {\n\to.EndTime = &v\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 (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 (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 GoogleCloudRetailV2alphaConditionTimeRangeResponseOutput) EndTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaConditionTimeRangeResponse) 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 (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 TimelineOutput) EndTime() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *Timeline) pulumi.IntPtrOutput { return v.EndTime }).(pulumi.IntPtrOutput)\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 *ApplianceClusterInstallPhase) SetEndTime(v time.Time) {\n\to.EndTime = &v\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 DataTransferConfigScheduleOptionsOutput) EndTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v DataTransferConfigScheduleOptions) *string { return v.EndTime }).(pulumi.StringPtrOutput)\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 (r *ReportTaskRequest) SetEndTime(endTime string) {\n r.EndTime = &endTime\n}", "func (s *GetProfileInput) SetEndTime(v time.Time) *GetProfileInput {\n\ts.EndTime = &v\n\treturn s\n}", "func (o *WorkflowServiceItemActionInstance) SetEndTime(v time.Time) {\n\to.EndTime = &v\n}", "func (r *ModifyTaskRequest) SetEndTime(endTime string) {\n r.EndTime = &endTime\n}", "func (o *OnpremUpgradePhase) SetEndTime(v time.Time) {\n\to.EndTime = &v\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 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 (m *SharePostRequestBody) GetEndDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n return m.endDateTime\n}", "func (object Object) EndTime(value time.Time) Object {\n\treturn object.Property(as.PropertyEndTime, value)\n}", "func (m *sdt) EndHour() int32 {\n\treturn m.endHourField\n}", "func (o *WorkflowCatalogServiceRequest) SetEndTime(v time.Time) {\n\to.EndTime = &v\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 (m *VulnEvidence) SetEndTime(in *google_protobuf.Timestamp) {\n\tm.EndTime = in\n}", "func (s *GetMetricDataInput) SetEndTime(v time.Time) *GetMetricDataInput {\n\ts.EndTime = &v\n\treturn s\n}", "func (o *OnpremUpgradePhase) 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 (_LvRecording *LvRecordingTransactor) SetEndTime(opts *bind.TransactOpts, _endTime *big.Int) (*types.Transaction, error) {\n\treturn _LvRecording.contract.Transact(opts, \"setEndTime\", _endTime)\n}", "func (s *GetRecommendationsInput) SetEndTime(v time.Time) *GetRecommendationsInput {\n\ts.EndTime = &v\n\treturn s\n}", "func (o RestoreResponseOutput) EndTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v RestoreResponse) string { return v.EndTime }).(pulumi.StringOutput)\n}", "func (s *PrefetchRetrieval) SetEndTime(v time.Time) *PrefetchRetrieval {\n\ts.EndTime = &v\n\treturn s\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 (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 (s *TrialComponent) SetEndTime(v time.Time) *TrialComponent {\n\ts.EndTime = &v\n\treturn s\n}", "func (s *GetMetricDataV2Input) SetEndTime(v time.Time) *GetMetricDataV2Input {\n\ts.EndTime = &v\n\treturn s\n}", "func (m *MarketHoursMutation) SetEndTime(t time.Time) {\n\tm.end_time = &t\n}", "func (o BaselineStrategyOutput) EndTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *BaselineStrategy) pulumi.StringOutput { return v.EndTime }).(pulumi.StringOutput)\n}", "func (s *UpdateTrialComponentInput) SetEndTime(v time.Time) *UpdateTrialComponentInput {\n\ts.EndTime = &v\n\treturn s\n}", "func (s *DescribeTrialComponentOutput) SetEndTime(v time.Time) *DescribeTrialComponentOutput {\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 (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 (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 (s *ListRecoveryPointsInput) SetEndTime(v time.Time) *ListRecoveryPointsInput {\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 (m *sdt) EndDateTime() int64 {\n\treturn m.endDateTimeField\n}", "func (s *GetMetricStatisticsInput) SetEndTime(v time.Time) *GetMetricStatisticsInput {\n\ts.EndTime = &v\n\treturn s\n}", "func (s *ListFindingsReportsInput) SetEndTime(v time.Time) *ListFindingsReportsInput {\n\ts.EndTime = &v\n\treturn s\n}", "func (s *CreateTrialComponentInput) SetEndTime(v time.Time) *CreateTrialComponentInput {\n\ts.EndTime = &v\n\treturn s\n}", "func (s *ConversationLogsDataSourceFilterBy) SetEndTime(v time.Time) *ConversationLogsDataSourceFilterBy {\n\ts.EndTime = &v\n\treturn s\n}", "func (s *TrialComponentSummary) SetEndTime(v time.Time) *TrialComponentSummary {\n\ts.EndTime = &v\n\treturn s\n}", "func (tsr *TestSuiteReporter) SetEndTime(t time.Time) {\n\ttsr.endTime = t\n\n\tif tsr.testSuite == nil {\n\t\treturn\n\t}\n\ttsr.testSuite.TimeInSeconds = tsr.Duration().Seconds()\n}", "func (o MetadataExportResponseOutput) EndTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v MetadataExportResponse) string { return v.EndTime }).(pulumi.StringOutput)\n}", "func (s *AutoMLCandidate) SetEndTime(v time.Time) *AutoMLCandidate {\n\ts.EndTime = &v\n\treturn s\n}", "func (s *PrefetchConsumption) SetEndTime(v time.Time) *PrefetchConsumption {\n\ts.EndTime = &v\n\treturn s\n}", "func (s *BatchGetFrameMetricDataInput) SetEndTime(v time.Time) *BatchGetFrameMetricDataInput {\n\ts.EndTime = &v\n\treturn s\n}", "func (s *ListSnapshotsInput) SetEndTime(v time.Time) *ListSnapshotsInput {\n\ts.EndTime = &v\n\treturn s\n}", "func (s *InferenceExperimentSchedule) SetEndTime(v time.Time) *InferenceExperimentSchedule {\n\ts.EndTime = &v\n\treturn s\n}", "func (c *ProjectsTracesListCall) EndTime(endTime string) *ProjectsTracesListCall {\n\tc.urlParams_.Set(\"endTime\", endTime)\n\treturn c\n}", "func (s *ImportJobProperties) SetEndTime(v time.Time) *ImportJobProperties {\n\ts.EndTime = &v\n\treturn s\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 LookupJobResultOutput) EndTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupJobResult) string { return v.EndTime }).(pulumi.StringOutput)\n}", "func (t *Timer) End() time.Time {\n\treturn t.end\n}", "func (s *GetMatchingJobOutput) SetEndTime(v time.Time) *GetMatchingJobOutput {\n\ts.EndTime = &v\n\treturn s\n}", "func (r *Reporter) SetEndTime(t time.Time) {\n\tr.endTime = t\n\n\tif r.report == nil {\n\t\treturn\n\t}\n\tr.report.TimeInSeconds = t.Sub(r.startTime).Seconds()\n}", "func (c *Container) SetEndTime(newEnd time.Time) {\n\tc.end = newEnd\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 (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}" ]
[ "0.8592755", "0.7491895", "0.7327237", "0.73128647", "0.7202728", "0.71574676", "0.7140883", "0.7082313", "0.7063966", "0.7059457", "0.69634634", "0.6931381", "0.6890082", "0.67958534", "0.6728343", "0.67127305", "0.67088944", "0.6631116", "0.6616934", "0.6547994", "0.6525623", "0.6488571", "0.64642924", "0.6463569", "0.6446536", "0.6428223", "0.6402636", "0.6368957", "0.6367753", "0.63654965", "0.63507515", "0.63374233", "0.6336237", "0.63300043", "0.6327515", "0.62935036", "0.62771714", "0.62760043", "0.6274604", "0.62711716", "0.6268429", "0.62558097", "0.62434036", "0.6215297", "0.6214315", "0.6212391", "0.620737", "0.62064326", "0.620588", "0.620588", "0.62001544", "0.6199933", "0.61961305", "0.6184114", "0.6183541", "0.61402124", "0.61151785", "0.6110377", "0.61076933", "0.6105413", "0.6100825", "0.6096354", "0.60956097", "0.60944843", "0.60784966", "0.6070895", "0.60647523", "0.60555965", "0.6041129", "0.6040183", "0.60397166", "0.6035819", "0.6029284", "0.6029284", "0.6028139", "0.60185987", "0.6017965", "0.60143626", "0.60129833", "0.60097545", "0.5997668", "0.59960014", "0.5994922", "0.5961401", "0.59608084", "0.59568775", "0.59552413", "0.59403473", "0.5940338", "0.593416", "0.5924543", "0.59233683", "0.5914819", "0.5908665", "0.5897975", "0.58969516", "0.58924824", "0.58882797", "0.5878576", "0.58777785" ]
0.8543022
1
NewClawbackVestingAccount returns a new ClawbackVestingAccount
NewClawbackVestingAccount возвращает новый ClawbackVestingAccount
func NewClawbackVestingAccount(baseAcc *authtypes.BaseAccount, funder sdk.AccAddress, originalVesting sdk.Coins, startTime int64, lockupPeriods, vestingPeriods Periods) *ClawbackVestingAccount { // copy and align schedules to avoid mutating inputs lp := make(Periods, len(lockupPeriods)) copy(lp, lockupPeriods) vp := make(Periods, len(vestingPeriods)) copy(vp, vestingPeriods) _, endTime := AlignSchedules(startTime, startTime, lp, vp) baseVestingAcc := &BaseVestingAccount{ BaseAccount: baseAcc, OriginalVesting: originalVesting, EndTime: endTime, } return &ClawbackVestingAccount{ BaseVestingAccount: baseVestingAcc, FunderAddress: funder.String(), StartTime: startTime, LockupPeriods: lp, VestingPeriods: vp, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "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() *Account {\n\treturn &Account{\n\t\tblocks: make(map[string]uint64),\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 (ak AccountKeeper) NewAccount(ctx sdk.Context, acc exported.Account) exported.Account {\n\t// FIXME: update account number\n\treturn acc\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 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 (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 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 (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 (*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 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(\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(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 NewAccount(txr *repository.Transactioner) repository.Account {\n\treturn &account{txr: txr}\n}", "func NewAccount(acc *types.Account) *Account {\n\treturn &Account{\n\t\tAccount: *acc,\n\t}\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 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 (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 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 (va *ClawbackVestingAccount) clawback(ctx sdk.Context, dest sdk.AccAddress, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) error {\n\t// Compute the clawback based on the account state only, and update account\n\ttoClawBack := va.computeClawback(ctx.BlockTime().Unix())\n\tif toClawBack.IsZero() {\n\t\treturn nil\n\t}\n\taddr := va.GetAddress()\n\tbondDenom := sk.BondDenom(ctx)\n\n\t// Compute the clawback based on bank balance and delegation, and update account\n\tencumbered := va.GetVestingCoins(ctx.BlockTime())\n\tbondedAmt := sk.GetDelegatorBonded(ctx, addr)\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, addr)\n\tbonded := sdk.NewCoins(sdk.NewCoin(bondDenom, bondedAmt))\n\tunbonding := sdk.NewCoins(sdk.NewCoin(bondDenom, unbondingAmt))\n\tunbonded := bk.GetAllBalances(ctx, addr)\n\ttoClawBack = va.updateDelegation(encumbered, toClawBack, bonded, unbonding, unbonded)\n\n\t// Write now now so that the bank module sees unvested tokens are unlocked.\n\t// Note that all store writes are aborted if there is a panic, so there is\n\t// no danger in writing incomplete results.\n\tak.SetAccount(ctx, va)\n\n\t// Now that future vesting events (and associated lockup) are removed,\n\t// the balance of the account is unlocked and can be freely transferred.\n\tspendable := bk.SpendableCoins(ctx, addr)\n\ttoXfer := coinsMin(toClawBack, spendable)\n\terr := bk.SendCoins(ctx, addr, dest, toXfer)\n\tif err != nil {\n\t\treturn err // shouldn't happen, given spendable check\n\t}\n\ttoClawBack = toClawBack.Sub(toXfer)\n\n\t// We need to traverse the staking data structures to update the\n\t// vesting account bookkeeping, and to recover more funds if necessary.\n\t// Staking is the only way unvested tokens should be missing from the bank balance.\n\n\t// If we need more, transfer UnbondingDelegations.\n\twant := toClawBack.AmountOf(bondDenom)\n\tunbondings := sk.GetUnbondingDelegations(ctx, addr, math.MaxUint16)\n\tfor _, unbonding := range unbondings {\n\t\tvalAddr, err := sdk.ValAddressFromBech32(unbonding.ValidatorAddress)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\ttransferred := sk.TransferUnbonding(ctx, addr, dest, valAddr, want)\n\t\twant = want.Sub(transferred)\n\t\tif !want.IsPositive() {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// If we need more, transfer Delegations.\n\tif want.IsPositive() {\n\t\tdelegations := sk.GetDelegatorDelegations(ctx, addr, math.MaxUint16)\n\t\tfor _, delegation := range delegations {\n\t\t\tvalidatorAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err) // shouldn't happen\n\t\t\t}\n\t\t\tvalidator, found := sk.GetValidator(ctx, validatorAddr)\n\t\t\tif !found {\n\t\t\t\t// validator has been removed\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\twantShares, err := validator.SharesFromTokensTruncated(want)\n\t\t\tif err != nil {\n\t\t\t\t// validator has no tokens\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttransferredShares := sk.TransferDelegation(ctx, addr, dest, delegation.GetValidatorAddr(), wantShares)\n\t\t\t// to be conservative in what we're clawing back, round transferred shares up\n\t\t\ttransferred := validator.TokensFromSharesRoundUp(transferredShares).RoundInt()\n\t\t\twant = want.Sub(transferred)\n\t\t\tif !want.IsPositive() {\n\t\t\t\t// Could be slightly negative, due to rounding?\n\t\t\t\t// Don't think so, due to the precautions above.\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// If we've transferred everything and still haven't transferred the desired clawback amount,\n\t// then the account must have most some unvested tokens from slashing.\n\treturn nil\n}", "func NewAccount(owner string) *Account {\n\treturn &Account{owner: owner, balance: 0}\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(firstName string) *Account {\n\tthis := Account{}\n\tthis.FirstName = firstName\n\treturn &this\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 (policy *ticketPolicy) OnCreateNewAccount(acc *types.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 NewTrainCar() TrainCar {\n c := TrainCar{name: \"TrainCar\", vehicle: \"TrainCar\", speed: 30, capacity: 30, railway: \"CNR\"}\n return c\n}", "func NewUserTeamwork()(*UserTeamwork) {\n m := &UserTeamwork{\n Entity: *NewEntity(),\n }\n return m\n}", "func NewAccount(email string) *Account {\n\treturn &Account{email: email}\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 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 MakeAccount(owner string) *Account {\n\taccount := Account{owner: owner, balance: 0}\n\treturn &account\n}", "func NewAccount(newid AccountIDType, newemail string) *Account {\n\treturn &Account{\n\t\tid: newid,\n\t\temail: newemail,\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 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 (ba *BankAccount) New() Resource {\n\tvar obj = &BankAccount{}\n\treturn obj\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 (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(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 (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 (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 NewAccount(addr, amount string) *Account {\n\tam := big.NewInt(0)\n\tam.SetString(amount, 0)\n\treturn &Account{Address: addr, Amount: am}\n}", "func newTicket(\n\tbeaconOutput []byte, // V_i\n\tstakerValue []byte, // Q_j\n\tvirtualStakerIndex *big.Int, // vs\n) (*ticket, error) {\n\tvalue, err := calculateTicketValue(beaconOutput, stakerValue, virtualStakerIndex)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ticket value calculation failed [%v]\", err)\n\t}\n\n\treturn &ticket{\n\t\tvalue: value,\n\t\tproof: &proof{\n\t\t\tstakerValue: stakerValue,\n\t\t\tvirtualStakerIndex: virtualStakerIndex,\n\t\t},\n\t}, nil\n}", "func NewBookingBusiness()(*BookingBusiness) {\n m := &BookingBusiness{\n Entity: *NewEntity(),\n }\n return m\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 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 *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 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 (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(accessKey string, secretKey string) *Coinsbank {\n\treturn &Coinsbank{\n\t\tAccessKey: accessKey,\n\t\tSecretKey: secretKey,\n\t}\n}", "func NewAccount(addr *Address) *Account {\n\treturn &Account{\n\t\taccount: common.NewAccount(common.BytesToAddress(addr.Bytes())),\n\t}\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 (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 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 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 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 (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 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 NewAllocAccount(val string) AllocAccountField {\n\treturn AllocAccountField{quickfix.FIXString(val)}\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 newBkCli() (*bkCli, error) {\n\tconfig := config.CurrentConfig()\n\n\tclient, err := newClient(config)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &bkCli{config, client}, 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 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 (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 NewAccount() *Account {\n\tacc := &Account{}\n\tpriv, pub := newKeyPair()\n\tacc.PriKey = priv\n\tacc.PubKey = pub\n\treturn acc\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 NewAccountClient(subscriptionID string) AccountClient {\n return NewAccountClientWithBaseURI(DefaultBaseURI, subscriptionID)\n}", "func (m *MockIAccountController) NewAccount(c *gin.Context) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"NewAccount\", c)\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 (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 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 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 newReconciledServiceAccount() *corev1.ServiceAccount {\n\treturn NewServiceAccount(newEventSource())()\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 CreateAccount (owner string) *Account {\n\taccount := Account{owner: owner, balance: 0}\n\treturn &account\n}", "func createAccountAndChangePassword(ctx context.Context, cryptohome *hwsec.CryptohomeClient, testPassword string, changePasswordShouldFail bool) error {\n\t// Create the account.\n\tif err := cryptohome.MountVault(ctx, util.PasswordLabel, hwsec.NewPassAuthConfig(username, oldPassword), true, hwsec.NewVaultConfig()); err != nil {\n\t\treturn errors.Wrap(err, \"failed to mount vault\")\n\t}\n\tif _, err := cryptohome.Unmount(ctx, username); err != nil {\n\t\treturn errors.Wrap(err, \"failed to unmount vault\")\n\t}\n\n\terr := cryptohome.ChangeVaultPassword(ctx, username, testPassword, util.PasswordLabel, newPassword)\n\tif !changePasswordShouldFail && err != nil {\n\t\treturn errors.Wrap(err, \"failed to change vault password\")\n\t}\n\tif changePasswordShouldFail && err == nil {\n\t\treturn errors.New(\"changing password unexpectedly succeeded\")\n\t}\n\treturn nil\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 NewFund(initialBalance int) *Fund {\n\t// We can return a pointer to a new struct without worrying about\n\t// whether it's on the stack or heap: Go figures that out for us.\n\treturn &Fund{\n\t\tbalance: initialBalance,\n\t}\n}", "func NewFund(initialBalance int) *Fund {\n\t// We can return a pointer to a new struct without worrying about\n\t// whether it's on the stack or heap: Go figures that out for us.\n\treturn &Fund{\n\t\tbalance: initialBalance,\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 (s SecureValueTypeRentalAgreement) construct() SecureValueTypeClass { return &s }", "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 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 NewBusinessScenarioPlanner()(*BusinessScenarioPlanner) {\n m := &BusinessScenarioPlanner{\n Entity: *NewEntity(),\n }\n return m\n}", "func createRequestAccount() *data.Account {\n\taccount := test.NewAccountDataFromFile(\"create-request.json\")\n\treturn &account.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 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 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 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 (account *Account) create(accountType string) *Account {\n\tfmt.Println(\"account creation with type\")\n\taccount.accountType = accountType\n\treturn account\n}", "func (r *Reconciler) CreateNooBaaAccount() error {\n\tlog := r.Logger\n\n\tif r.NooBaaAccount == nil {\n\t\treturn fmt.Errorf(\"NooBaaAccount not loaded %#v\", r)\n\t}\n\n\tcreateAccountParams := nb.CreateAccountParams{\n\t\tName: r.NooBaaAccount.Name,\n\t\tEmail: r.NooBaaAccount.Name,\n\t\tDefaultResource: r.NooBaaAccount.Spec.DefaultResource,\n\t\tHasLogin: false,\n\t\tS3Access: true,\n\t\tAllowBucketCreate: r.NooBaaAccount.Spec.AllowBucketCreate,\n\t}\n\n\tif r.NooBaaAccount.Spec.NsfsAccountConfig != nil {\n\t\tcreateAccountParams.NsfsAccountConfig = &nbv1.AccountNsfsConfig{\n\t\t\tUID: r.NooBaaAccount.Spec.NsfsAccountConfig.UID,\n\t\t\tGID: r.NooBaaAccount.Spec.NsfsAccountConfig.GID,\n\t\t\tNewBucketsPath: r.NooBaaAccount.Spec.NsfsAccountConfig.NewBucketsPath,\n\t\t\tNsfsOnly: r.NooBaaAccount.Spec.NsfsAccountConfig.NsfsOnly,\n\t\t}\n\t}\n\n\taccountInfo, err := r.NBClient.CreateAccountAPI(createAccountParams)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar accessKeys nb.S3AccessKeys\n\t// if we didn't get the access keys in the create_account reply we might be talking to an older noobaa version (prior to 5.1)\n\t// in that case try to get it using read account\n\tif len(accountInfo.AccessKeys) == 0 {\n\t\tlog.Info(\"CreateAccountAPI did not return access keys. calling ReadAccountAPI to get keys..\")\n\t\treadAccountReply, err := r.NBClient.ReadAccountAPI(nb.ReadAccountParams{Email: r.NooBaaAccount.Name})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\taccessKeys = readAccountReply.AccessKeys[0]\n\t} else {\n\t\taccessKeys = accountInfo.AccessKeys[0]\n\t}\n\tr.Secret.StringData = map[string]string{}\n\tr.Secret.StringData[\"AWS_ACCESS_KEY_ID\"] = accessKeys.AccessKey\n\tr.Secret.StringData[\"AWS_SECRET_ACCESS_KEY\"] = accessKeys.SecretKey\n\tr.Own(r.Secret)\n\terr = r.Client.Create(r.Ctx, r.Secret)\n\tif err != nil {\n\t\tr.Logger.Errorf(\"got error on NooBaaAccount creation. error: %v\", err)\n\t\treturn err\n\t}\n\n\tlog.Infof(\"✅ Successfully created account %q\", r.NooBaaAccount.Name)\n\treturn 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 newPerson(name string,class string, nationality string ) *Person {\n\treturn &Person{name: name,job: class, nationality: nationality}\n\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 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 new(master_key string) Ca {\n\tcatls, err := tls.LoadX509KeyPair(\"../storage/root-certificate/ca_cert.pem\", \"../storage/root-certificate/ca_key.pem\")\n\tcheck(err)\n\tfirst_start_time := time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC).AddDate(0, 0, 0)\n\treturn Ca{catls, master_key, first_start_time}\n}" ]
[ "0.63165385", "0.62145144", "0.6156019", "0.6112193", "0.60393506", "0.6007511", "0.5856643", "0.58285093", "0.58285093", "0.5770267", "0.56909066", "0.561485", "0.551723", "0.5479558", "0.54709643", "0.54680747", "0.5435082", "0.54297704", "0.5414012", "0.54114395", "0.54044974", "0.54028434", "0.53938144", "0.5376972", "0.5375555", "0.5357546", "0.5350232", "0.53483385", "0.53322136", "0.5318299", "0.5315906", "0.5282893", "0.52680606", "0.526588", "0.5253027", "0.52391535", "0.5237239", "0.5231092", "0.52102333", "0.5208385", "0.52044654", "0.52017343", "0.51992774", "0.51855445", "0.5182337", "0.51620185", "0.51544577", "0.5117961", "0.5104099", "0.5101882", "0.5093717", "0.5089297", "0.508741", "0.50854784", "0.508262", "0.50777924", "0.5066441", "0.50594157", "0.50582904", "0.5055537", "0.5054489", "0.5051452", "0.5046636", "0.50377655", "0.50345886", "0.5033626", "0.5021296", "0.5017964", "0.50127566", "0.50118977", "0.5010847", "0.5001309", "0.49991637", "0.49952903", "0.49897137", "0.4981563", "0.4971323", "0.49693838", "0.49655354", "0.49554536", "0.49532548", "0.49493697", "0.49493697", "0.4947169", "0.49416807", "0.493833", "0.49324596", "0.49222118", "0.48960105", "0.48875386", "0.48835057", "0.4882358", "0.48815426", "0.48782998", "0.48764876", "0.4876422", "0.48762697", "0.48731366", "0.48709914", "0.48674107" ]
0.75940603
0
GetVestingCoins returns the total number of vesting coins. If no coins are vesting, nil is returned.
GetVestingCoins возвращает общее количество вesting-монет. Если нет вesting-монет, возвращается nil.
func (va ClawbackVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins { return va.OriginalVesting.Sub(va.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 (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 (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 (keeper BaseViewKeeper) HasCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) bool {\n\treturn hasCoins(ctx, keeper.am, addr, amt)\n}", "func (plva PermanentLockedAccount) LockedCoins(_ sdk.Context) sdk.Coins {\n\treturn plva.BaseVestingAccount.LockedCoinsFromVesting(plva.OriginalVesting)\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 (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 (a *Agent) GetPeersCount() uint32 {\n\treturn atomic.LoadUint32(&a.peersCount)\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 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 *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 (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 (_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 (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 (_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}" ]
[ "0.74396104", "0.726373", "0.714508", "0.7126855", "0.7010945", "0.670897", "0.66787076", "0.66363263", "0.6620459", "0.65084815", "0.6413031", "0.5598332", "0.55388", "0.5478214", "0.5397174", "0.535151", "0.53034747", "0.5291319", "0.5265547", "0.5263068", "0.52396154", "0.52286416", "0.5193281", "0.50844795", "0.5011713", "0.49284658", "0.49219754", "0.4904928", "0.48519877", "0.48489055", "0.48284203", "0.47899073", "0.47672805", "0.4611372", "0.45811477", "0.45748222", "0.45643818", "0.4546548", "0.45288718", "0.45240188", "0.45172656", "0.4512356", "0.44718787", "0.44657588", "0.4456784", "0.44515997", "0.4415981", "0.4414714", "0.44144577", "0.44108146", "0.4405778", "0.44037047", "0.44000402", "0.43852434", "0.43783808", "0.4366527", "0.43438405", "0.43292856", "0.4327142", "0.432488", "0.43184718", "0.43085203", "0.4295404", "0.42843035", "0.42677224", "0.425481", "0.4251709", "0.42239136", "0.422126", "0.42055273", "0.41869", "0.4186892", "0.41824117", "0.41807854", "0.4179897", "0.4177675", "0.41754848", "0.4172519", "0.41715524", "0.41699547", "0.4166136", "0.4165427", "0.41619334", "0.41605112", "0.41544116", "0.41536543", "0.41494378", "0.41377124", "0.41337442", "0.4130032", "0.412577", "0.4120538", "0.41203645", "0.41160396", "0.4106734", "0.41003996", "0.40959004", "0.4094604", "0.4094378", "0.40940142" ]
0.72693485
1
GetVestingPeriods returns vesting periods associated with periodic vesting account.
GetVestingPeriods возвращает периоды востребования, связанные с аккаунтом периодического востребования.
func (va ClawbackVestingAccount) GetVestingPeriods() Periods { return va.VestingPeriods }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (pva PeriodicVestingAccount) GetVestingPeriods() Periods {\n\treturn pva.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 (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 ElastigroupScalingDownPolicyOutput) EvaluationPeriods() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v ElastigroupScalingDownPolicy) *int { return v.EvaluationPeriods }).(pulumi.IntPtrOutput)\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 (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 (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 (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 (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 NewSLAGetExclusionPeriodsParamsWithTimeout(timeout time.Duration) *SLAGetExclusionPeriodsParams {\n\tvar ()\n\treturn &SLAGetExclusionPeriodsParams{\n\n\t\ttimeout: timeout,\n\t}\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 (plva PermanentLockedAccount) GetVestingCoins(_ time.Time) sdk.Coins {\n\treturn plva.OriginalVesting\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 (h *stubDriveHandler) GetDrives() []models.Drive {\n\treturn h.drives\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 (o ElastigroupIntegrationEcsAutoscaleDownOutput) EvaluationPeriods() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v ElastigroupIntegrationEcsAutoscaleDown) *int { return v.EvaluationPeriods }).(pulumi.IntPtrOutput)\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 (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 (_Vault *VaultCallerSession) GetDecimals(token common.Address) (uint8, error) {\n\treturn _Vault.Contract.GetDecimals(&_Vault.CallOpts, token)\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 InstanceOutput) Period() pulumi.IntOutput {\n\treturn o.ApplyT(func(v *Instance) pulumi.IntOutput { return v.Period }).(pulumi.IntOutput)\n}", "func (o ElastigroupIntegrationNomadAutoscaleDownOutput) EvaluationPeriods() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v ElastigroupIntegrationNomadAutoscaleDown) *int { return v.EvaluationPeriods }).(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 (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 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 (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 (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 (v PingSlotPeriod) MarshalJSONPB(m *jsonpb.Marshaler) ([]byte, error) {\n\treturn marshalJSONPBEnum(m, PingSlotPeriod_name, int32(v))\n}", "func (o *SLAGetExclusionPeriodsParams) WithTimeout(timeout time.Duration) *SLAGetExclusionPeriodsParams {\n\to.SetTimeout(timeout)\n\treturn o\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 GetDeploymentVolumes(item interface{}) []corev1.Volume {\n\treturn item.(appsv1.Deployment).Spec.Template.Spec.Volumes\n}", "func (test *Test) GetDomains(projectName string) ([]models.Domain, error) {\n\treturn tests.NormalDomains, nil\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 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}", "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 (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}" ]
[ "0.82607967", "0.53933996", "0.51751536", "0.5136177", "0.5023484", "0.49357113", "0.4917464", "0.47208306", "0.47143596", "0.45715773", "0.45275274", "0.45155838", "0.44273278", "0.44169536", "0.44071308", "0.43515027", "0.42970163", "0.41897523", "0.41696903", "0.41315487", "0.40534994", "0.4024805", "0.3987746", "0.39256877", "0.39178488", "0.39072612", "0.39072612", "0.38997084", "0.38981694", "0.38896894", "0.38864052", "0.3884726", "0.38830853", "0.3860149", "0.38553673", "0.38529113", "0.38482285", "0.38334394", "0.38258576", "0.38249928", "0.3821619", "0.3813515", "0.38066056", "0.38053465", "0.37828732", "0.37766388", "0.37707412", "0.37658718", "0.3765389", "0.37535924", "0.37509766", "0.3742345", "0.37401107", "0.37369865", "0.37331843", "0.37278366", "0.3720804", "0.37195626", "0.37173465", "0.37105906", "0.37092373", "0.37053418", "0.36950052", "0.36942267", "0.36917034", "0.36850712", "0.3683275", "0.36812162", "0.36787438", "0.36743674", "0.36697808", "0.3665709", "0.36652938", "0.3657308", "0.3655877", "0.36511636", "0.3648951", "0.3635065", "0.36324564", "0.3628458", "0.36277944", "0.36268395", "0.362216", "0.3618688", "0.3618097", "0.36128396", "0.361273", "0.3604821", "0.3601217", "0.35980293", "0.35937566", "0.3593497", "0.35911334", "0.35883754", "0.35852683", "0.35820916", "0.35753784", "0.3555677", "0.35535908", "0.35534784" ]
0.8009713
1
coinEq returns whether two Coins are equal. The IsEqual() method can panic.
coinEq возвращает значение, указывающее, равны ли два Coin. Метод IsEqual() может вызвать панику.
func coinEq(a, b sdk.Coins) bool { return a.IsAllLTE(b) && b.IsAllLTE(a) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (coin Coin) IsEqual(other Coin) bool {\n\treturn coin.Amount.Equal(other.Amount)\n}", "func (v Coin) Equal(o Coin) bool {\n\treturn v.Amount.Equal(o.Amount) &&\n\t\tv.CoinIdentifier.Equal(o.CoinIdentifier)\n}", "func (n *Uint256) Eq(n2 *Uint256) bool {\n\treturn n.n[0] == n2.n[0] && n.n[1] == n2.n[1] && n.n[2] == n2.n[2] &&\n\t\tn.n[3] == n2.n[3]\n}", "func (v Currency) Equal(o Currency) bool {\n\treturn v.Decimals == o.Decimals &&\n\t\tstring(v.Metadata) == string(o.Metadata) &&\n\t\tv.Symbol == o.Symbol\n}", "func (v CoinChange) Equal(o CoinChange) bool {\n\treturn v.CoinAction == o.CoinAction &&\n\t\tv.CoinIdentifier.Equal(o.CoinIdentifier)\n}", "func (x *Money) Equal(y *Money) bool {\n\tif x.Currency != y.Currency {\n\t\treturn false\n\t}\n\treturn x.Amount.Equal(y.Amount)\n}", "func (x *Secp256k1N) Eq(y *Secp256k1N) bool {\n\t// TODO: More efficient implementation/\n\tvar xNorm, yNorm = *x, *y\n\txNorm.Normalize()\n\tyNorm.Normalize()\n\treturn xNorm.limbs[0] == yNorm.limbs[0] &&\n\t\txNorm.limbs[1] == yNorm.limbs[1] &&\n\t\txNorm.limbs[2] == yNorm.limbs[2] &&\n\t\txNorm.limbs[3] == yNorm.limbs[3] &&\n\t\txNorm.limbs[4] == yNorm.limbs[4]\n}", "func (v AccountCoinsRequest) Equal(o AccountCoinsRequest) bool {\n\treturn v.AccountIdentifier.Equal(o.AccountIdentifier) &&\n\t\tlen(v.Currencies) == len(o.Currencies) &&\n\t\tcurrencySliceEqual(v.Currencies, o.Currencies) &&\n\t\tv.IncludeMempool == o.IncludeMempool\n}", "func (bal Balance) Equals(other Balance) bool {\r\n\treturn bal.Coins == other.Coins && bal.Hours == other.Hours\r\n}", "func (m *Money) Equals(n *Money) bool {\n\treturn m.Amount() == n.Amount() && m.Currency() == n.Currency()\n}", "func (c *Coinbase) Equals(t Transaction) bool {\n\n\tother, ok := t.(*Coinbase)\n\tif !ok {\n\t\treturn false\n\t}\n\n\tif !bytes.Equal(c.R, other.R) {\n\t\treturn false\n\t}\n\n\tif !bytes.Equal(c.Score, other.Score) {\n\t\treturn false\n\t}\n\n\tif !bytes.Equal(c.Proof, other.Proof) {\n\t\treturn false\n\t}\n\n\tif !c.Rewards.Equals(other.Rewards) {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (c *Currency) Equals(other *Currency) bool {\n\treturn c == other ||\n\t\t(c.Decimals == other.Decimals && c.Symbol == other.Symbol && c.Name == other.Name)\n}", "func (v AccountCoinsResponse) Equal(o AccountCoinsResponse) bool {\n\treturn v.BlockIdentifier.Equal(o.BlockIdentifier) &&\n\t\tlen(v.Coins) == len(o.Coins) &&\n\t\tcoinSliceEqual(v.Coins, o.Coins) &&\n\t\tstring(v.Metadata) == string(o.Metadata)\n}", "func (m Money) Equals(other Money) bool {\n\treturn m.currency.Equals(other.currency) && m.Amount().Equals(other.Amount())\n}", "func (c1 *Certificate) Equal(c2 *Certificate) bool {\n\treturn reflect.DeepEqual(c1.Certificate, c2.Certificate)\n}", "func Eq(one, other interface{}) bool {\n\treturn reflect.DeepEqual(one, other)\n}", "func (tx *Transaction) IsCoinbase() bool {\n\treturn len(tx.Vin) == 1 && len(tx.Vin[0].Txid) == 0 && tx.Vin[0].Vout == -1\n}", "func (tx Transaction) IsCoinbase() bool {\n\treturn len(tx.Vin) == 1 && len(tx.Vin[0].Txid) == 0 && tx.Vin[0].Vout == -1\n}", "func (b Balance) Equal(b2 Balance) bool {\n\treturn b.Int != nil && b2.Int != nil && b.Int.Cmp(b2.Int) == 0\n}", "func Eq(a, b interface{}, f Func) bool {\n\treturn f(a, b) == 0\n}", "func (backend *Backend) Coin(code coinpkg.Code) (coinpkg.Coin, error) {\n\tdefer backend.coinsLock.Lock()()\n\tcoin, ok := backend.coins[code]\n\tif ok {\n\t\treturn coin, nil\n\t}\n\tdbFolder := backend.arguments.CacheDirectoryPath()\n\n\terc20Token := erc20TokenByCode(code)\n\tbtcFormatUnit := backend.config.AppConfig().Backend.BtcUnit\n\tswitch {\n\tcase code == coinpkg.CodeRBTC:\n\t\tservers := backend.defaultElectrumXServers(code)\n\t\tcoin = btc.NewCoin(coinpkg.CodeRBTC, \"Bitcoin Regtest\", \"RBTC\", coinpkg.BtcUnitDefault, &chaincfg.RegressionNetParams, dbFolder, servers, \"\", backend.socksProxy)\n\tcase code == coinpkg.CodeTBTC:\n\t\tservers := backend.defaultElectrumXServers(code)\n\t\tcoin = btc.NewCoin(coinpkg.CodeTBTC, \"Bitcoin Testnet\", \"TBTC\", btcFormatUnit, &chaincfg.TestNet3Params, dbFolder, servers,\n\t\t\t\"https://blockstream.info/testnet/tx/\", backend.socksProxy)\n\tcase code == coinpkg.CodeBTC:\n\t\tservers := backend.defaultElectrumXServers(code)\n\t\tcoin = btc.NewCoin(coinpkg.CodeBTC, \"Bitcoin\", \"BTC\", btcFormatUnit, &chaincfg.MainNetParams, dbFolder, servers,\n\t\t\t\"https://blockstream.info/tx/\", backend.socksProxy)\n\tcase code == coinpkg.CodeTLTC:\n\t\tservers := backend.defaultElectrumXServers(code)\n\t\tcoin = btc.NewCoin(coinpkg.CodeTLTC, \"Litecoin Testnet\", \"TLTC\", coinpkg.BtcUnitDefault, &ltc.TestNet4Params, dbFolder, servers,\n\t\t\t\"https://sochain.com/tx/LTCTEST/\", backend.socksProxy)\n\tcase code == coinpkg.CodeLTC:\n\t\tservers := backend.defaultElectrumXServers(code)\n\t\tcoin = btc.NewCoin(coinpkg.CodeLTC, \"Litecoin\", \"LTC\", coinpkg.BtcUnitDefault, &ltc.MainNetParams, dbFolder, servers,\n\t\t\t\"https://blockchair.com/litecoin/transaction/\", backend.socksProxy)\n\tcase code == coinpkg.CodeETH:\n\t\tetherScan := etherscan.NewEtherScan(\"https://api.etherscan.io/api\", backend.etherScanHTTPClient)\n\t\tcoin = eth.NewCoin(etherScan, code, \"Ethereum\", \"ETH\", \"ETH\", params.MainnetChainConfig,\n\t\t\t\"https://etherscan.io/tx/\",\n\t\t\tetherScan,\n\t\t\tnil)\n\tcase code == coinpkg.CodeGOETH:\n\t\tetherScan := etherscan.NewEtherScan(\"https://api-goerli.etherscan.io/api\", backend.etherScanHTTPClient)\n\t\tcoin = eth.NewCoin(etherScan, code, \"Ethereum Goerli\", \"GOETH\", \"GOETH\", params.GoerliChainConfig,\n\t\t\t\"https://goerli.etherscan.io/tx/\",\n\t\t\tetherScan,\n\t\t\tnil)\n\tcase erc20Token != nil:\n\t\tetherScan := etherscan.NewEtherScan(\"https://api.etherscan.io/api\", backend.etherScanHTTPClient)\n\t\tcoin = eth.NewCoin(etherScan, erc20Token.code, erc20Token.name, erc20Token.unit, \"ETH\", params.MainnetChainConfig,\n\t\t\t\"https://etherscan.io/tx/\",\n\t\t\tetherScan,\n\t\t\terc20Token.token,\n\t\t)\n\tdefault:\n\t\treturn nil, errp.Newf(\"unknown coin code %s\", code)\n\t}\n\tbackend.coins[code] = coin\n\tcoin.Observe(backend.Notify)\n\treturn coin, nil\n}", "func (d Decimal) Equal(d2 Decimal) bool {\n\treturn d.Cmp(d2) == 0\n}", "func (d Decimal) Equal(d2 Decimal) bool {\n\treturn d.Cmp(d2) == 0\n}", "func EqDeeply(got, expected any) bool {\n\treturn deepValueEqualOK(reflect.ValueOf(got), reflect.ValueOf(expected))\n}", "func (mm MoneyMarket) Equal(mmCompareTo MoneyMarket) bool {\n\tif mm.Denom != mmCompareTo.Denom {\n\t\treturn false\n\t}\n\tif !mm.BorrowLimit.Equal(mmCompareTo.BorrowLimit) {\n\t\treturn false\n\t}\n\tif mm.SpotMarketID != mmCompareTo.SpotMarketID {\n\t\treturn false\n\t}\n\tif !mm.ConversionFactor.Equal(mmCompareTo.ConversionFactor) {\n\t\treturn false\n\t}\n\tif !mm.InterestRateModel.Equal(mmCompareTo.InterestRateModel) {\n\t\treturn false\n\t}\n\tif !mm.ReserveFactor.Equal(mmCompareTo.ReserveFactor) {\n\t\treturn false\n\t}\n\tif !mm.AuctionSize.Equal(mmCompareTo.AuctionSize) {\n\t\treturn false\n\t}\n\tif !mm.KeeperRewardPercentage.Equal(mmCompareTo.KeeperRewardPercentage) {\n\t\treturn false\n\t}\n\treturn true\n}", "func (m *Money) Equals(tm *Money) bool {\n\tif m.currency != tm.currency {\n\t\treturn false\n\t}\n\tif m.amount != tm.amount {\n\t\treturn false\n\t}\n\treturn true\n}", "func (t *Transaction) IsCoinbase() bool {\n\treturn len(t.Vint) == 1 && len(t.Vint[0].TxHash) == 0 && t.Vint[0].Index == -1\n}", "func (txn *Transaction) IsCoinbase() bool {\n\treturn len(txn.Inputs) == 1 && len(txn.Inputs[0].ID) == 0 && txn.Inputs[0].OutIndex == -1\n}", "func (v CoinIdentifier) Equal(o CoinIdentifier) bool {\n\treturn v.Identifier == o.Identifier\n}", "func (tx *Transaction) IsCoinbase() bool {\n\treturn len(tx.Inputs) == 1 && len(tx.Inputs[0].ID) == 0 && tx.Inputs[0].Out == -1\n}", "func (tx *Transaction) IsCoinbase() bool {\n\treturn len(tx.Inputs) == 1 && len(tx.Inputs[0].ID) == 0 && tx.Inputs[0].Out == -1\n}", "func (s Balance) Equal(t Balance, opts ...Options) bool {\n\tif !equalPointers(s.Algorithm, t.Algorithm) {\n\t\treturn false\n\t}\n\n\tif s.HashExpression != t.HashExpression {\n\t\treturn false\n\t}\n\n\tif s.HdrName != t.HdrName {\n\t\treturn false\n\t}\n\n\tif s.HdrUseDomainOnly != t.HdrUseDomainOnly {\n\t\treturn false\n\t}\n\n\tif s.RandomDraws != t.RandomDraws {\n\t\treturn false\n\t}\n\n\tif s.RdpCookieName != t.RdpCookieName {\n\t\treturn false\n\t}\n\n\tif s.URIDepth != t.URIDepth {\n\t\treturn false\n\t}\n\n\tif s.URILen != t.URILen {\n\t\treturn false\n\t}\n\n\tif s.URIPathOnly != t.URIPathOnly {\n\t\treturn false\n\t}\n\n\tif s.URIWhole != t.URIWhole {\n\t\treturn false\n\t}\n\n\tif s.URLParam != t.URLParam {\n\t\treturn false\n\t}\n\n\tif s.URLParamCheckPost != t.URLParamCheckPost {\n\t\treturn false\n\t}\n\n\tif s.URLParamMaxWait != t.URLParamMaxWait {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (recv *ParamSpecUChar) Equals(other *ParamSpecUChar) bool {\n\treturn other.ToC() == recv.ToC()\n}", "func (c1 city) Equal(c2 city) bool {\n\tif c1.name != c2.name {\n\t\treturn false\n\t}\n\tif c1.population != c2.population {\n\t\treturn false\n\t}\n\tif c1.cost != c2.cost {\n\t\treturn false\n\t}\n\tif c1.climate != c2.climate {\n\t\treturn false\n\t}\n\treturn true\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 (t *Transaction) IsCoinbase() bool {\n\t// Check to see there is just 1 input and that it is not linked to any other transactions\n\treturn len(t.Inputs) == 1 && len(t.Inputs[0].ID) == 0 && t.Inputs[0].Out == -1\n}", "func equal(lhs, rhs semantic.Expression) semantic.Expression {\n\treturn &semantic.BinaryOp{Type: semantic.BoolType, LHS: lhs, Operator: ast.OpEQ, RHS: rhs}\n}", "func (peer *peerImp) Equal(otherPeer Peer) bool {\n\treturn peer.id.Equal(otherPeer.GetID())\n}", "func TestCoinChange(t *testing.T) {\n\ttest(t, coinChange)\n}", "func rcEqEq(p *TCompiler, code *TCode) (*value.Value, error) {\n\tv := value.EqEq(p.regGet(code.B), p.regGet(code.C))\n\tp.regSet(code.A, v)\n\tp.moveNext()\n\treturn v, nil\n}", "func (state VPCState) Equal(b VPCState) (result bool) {\n\tif bytes.Equal(state.ID, b.ID) &&\n\t\tstate.Version.Cmp(b.Version) == 0 &&\n\t\tstate.BlockedReceiver.Cmp(b.BlockedReceiver) == 0 &&\n\t\tstate.BlockedSender.Cmp(b.BlockedSender) == 0 {\n\t\treturn true\n\t}\n\treturn false\n}", "func NewCoin(\n\tname string,\n\tunit string,\n\tnet *chaincfg.Params,\n\tdbFolder string,\n\tservers []*rpc.ServerInfo,\n\tblockExplorerTxPrefix string,\n\tratesUpdater coinpkg.RatesUpdater,\n) *Coin {\n\tcoin := &Coin{\n\t\tname: name,\n\t\tunit: unit,\n\t\tnet: net,\n\t\tdbFolder: dbFolder,\n\t\tservers: servers,\n\t\tblockExplorerTxPrefix: blockExplorerTxPrefix,\n\t\tratesUpdater: ratesUpdater,\n\n\t\tlog: logging.Get().WithGroup(\"coin\").WithField(\"name\", name),\n\t}\n\treturn coin\n}", "func (rt *RecvTxOut) IsCoinbase() bool {\n\tif rt.recvTxOut.block == nil {\n\t\treturn false\n\t}\n\treturn rt.recvTxOut.block.Index == 0\n}", "func NewCoin(\n\tcode string,\n\tunit string,\n\tfeeUnit string,\n\tnet *params.ChainConfig,\n\tblockExplorerTxPrefix string,\n\tetherScanURL string,\n\tnodeURL string,\n\terc20Token *erc20.Token,\n) *Coin {\n\treturn &Coin{\n\t\tcode: code,\n\t\tunit: unit,\n\t\tfeeUnit: feeUnit,\n\t\tnet: net,\n\t\tblockExplorerTxPrefix: blockExplorerTxPrefix,\n\t\tnodeURL: nodeURL,\n\t\tetherScanURL: etherScanURL,\n\t\terc20Token: erc20Token,\n\n\t\tlog: logging.Get().WithGroup(\"coin\").WithField(\"code\", code),\n\t}\n}", "func (bits *BitArray) Eq(obits *BitArray) bool {\n\tif bits.length != obits.length {\n\t\treturn false\n\t}\n\n\tfor i := 0; i < bits.lenpad; i += _BytesPW {\n\t\twself := bytes2word(bits.bytes[i : i+_BytesPW])\n\t\twother := bytes2word(obits.bytes[i : i+_BytesPW])\n\t\tif wself != wother {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func DeepEq(a, b Value) bool {\n\treturn reflect.DeepEqual(a, b)\n}", "func DeepEq(a, b Value) bool {\n\treturn reflect.DeepEqual(a, b)\n}", "func (r *Repo) CommitsEquivalent(c1 string, c2 string) (bool, error) {\n\tif c1 == \"\" {\n\t\treturn c2 == \"\", nil\n\t} else if c2 == \"\" {\n\t\treturn false, nil\n\t}\n\n\tcommits, err := r.downloader.CommitsFor(r.Path(), c1)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tfor _, c := range commits {\n\t\tif c == c2 {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\treturn false, nil\n}", "func (recv *InitiallyUnowned) Equals(other *InitiallyUnowned) bool {\n\treturn other.ToC() == recv.ToC()\n}", "func TestIsCoinbaseTx(t *testing.T) {\n\ttests := []struct {\n\t\tname string // test description\n\t\ttx string // transaction to test\n\t\twantPreTrsy bool // expected coinbase result before treasury active\n\t\twantPostTrsy bool // expected coinbase result after treasury active\n\t}{{\n\t\tname: \"mainnet block 2 coinbase\",\n\t\ttx: \"010000000100000000000000000000000000000000000000000000000000000\" +\n\t\t\t\"00000000000ffffffff00ffffffff03fa1a981200000000000017a914f59161\" +\n\t\t\t\"58e3e2c4551c1796708db8367207ed13bb8700000000000000000000266a240\" +\n\t\t\t\"2000000000000000000000000000000000000000000000000000000ffa310d9\" +\n\t\t\t\"a6a9588edea1906f0000000000001976a9148ffe7a49ecf0f4858e7a5215530\" +\n\t\t\t\"2177398d2296988ac000000000000000001d8bc28820000000000000000ffff\" +\n\t\t\t\"ffff0800002f646372642f\",\n\t\twantPreTrsy: true,\n\t\twantPostTrsy: false,\n\t}, {\n\t\tname: \"modified mainnet block 2 coinbase: tx version 3\",\n\t\ttx: \"030000000100000000000000000000000000000000000000000000000000000\" +\n\t\t\t\"00000000000ffffffff00ffffffff02fa1a981200000000000017a914f59161\" +\n\t\t\t\"58e3e2c4551c1796708db8367207ed13bb8700000000000000000000266a240\" +\n\t\t\t\"2000000000000000000000000000000000000000000000000000000ffa310d9\" +\n\t\t\t\"a6a9588e000000000000000001d8bc28820000000000000000ffffffff08000\" +\n\t\t\t\"02f646372642f\",\n\t\twantPreTrsy: true,\n\t\twantPostTrsy: true,\n\t}, {\n\t\tname: \"modified mainnet block 2 coinbase: tx version 3, no miner payout\",\n\t\ttx: \"030000000100000000000000000000000000000000000000000000000000000\" +\n\t\t\t\"00000000000ffffffff00ffffffff02fa1a981200000000000017a914f59161\" +\n\t\t\t\"58e3e2c4551c1796708db8367207ed13bb8700000000000000000000266a240\" +\n\t\t\t\"2000000000000000000000000000000000000000000000000000000ffa310d9\" +\n\t\t\t\"a6a9588e000000000000000001d8bc28820000000000000000ffffffff08000\" +\n\t\t\t\"02f646372642f\",\n\t\twantPreTrsy: true,\n\t\twantPostTrsy: true,\n\t}, {\n\t\tname: \"mainnet block 3, tx[1] (one input), not coinbase\",\n\t\ttx: \"0100000001e68bcb9222c7f6336e865c81d7fd3e4b3244cd83998ac9767efcb\" +\n\t\t\t\"355b3cd295efe02000000ffffffff01105ba3940600000000001976a914dcfd\" +\n\t\t\t\"20801304752f618295dfe0a4c044afcfde3a88ac000000000000000001e04aa\" +\n\t\t\t\"7940600000001000000000000006b48304502210089d763b0c28314b5eb0d4c\" +\n\t\t\t\"97e0183a78bb4a656dcbcd293d29d91921a64c55af02203554e76f432f73862\" +\n\t\t\t\"edd4f2ed80a4599141b13c6ac2406158b05a97c6867a1ba01210244709193c0\" +\n\t\t\t\"5a649df0fb0a96180ec1a8e3cbcc478dc9c4a69a3ec5aba1e97a79\",\n\t\twantPreTrsy: false,\n\t\twantPostTrsy: false,\n\t}, {\n\t\tname: \"mainnet block 373, tx[5] (two inputs), not coinbase\",\n\t\ttx: \"010000000201261057a5ecaf6edede86c5446c62f067f30d654117668325090\" +\n\t\t\t\"9ac3e45bec00100000000ffffffff03c65ad19cb990cc916e38dc94f0255f34\" +\n\t\t\t\"4c5e9b7af3b69bfa19931f6027e44c0100000000ffffffff02c1c5760000000\" +\n\t\t\t\"00000001976a914e07c0b2a499312f5d95e3bd4f126e618087a15a588ac402c\" +\n\t\t\t\"42060000000000001976a91411f2b3135e457259009bdd14cfcb942eec58bd7\" +\n\t\t\t\"a88ac0000000000000000023851f6050000000073010000040000006a473044\" +\n\t\t\t\"022009ff5aed5d2e5eeec89319d0a700b7abdf842e248641804c82dee17df44\" +\n\t\t\t\"6c24202207c252cc36199ea8a6cc71d2252a3f7e61f9cce272dff82c5818e3b\" +\n\t\t\t\"f08167e3a6012102773925f9ee53837aa0efba2212f71ee8ab20aeb603fa732\" +\n\t\t\t\"4a8c2555efe5c482709ec0e010000000025010000050000006a473044022011\" +\n\t\t\t\"65136a2b792cc6d7e75f576ed64e1919cbf954afb989f8590844a628e58def0\" +\n\t\t\t\"2206ba7e60f5ae9810794297359cc883e7ff97ecd21bc7177fcc668a84f64a4\" +\n\t\t\t\"b9120121026a4151513b4e6650e3d213451037cd6b78ed829d12ed1d43d5d34\" +\n\t\t\t\"ce0834831e9\",\n\t\twantPreTrsy: false,\n\t\twantPostTrsy: false,\n\t}, {\n\t\tname: \"simnet block 32 coinbase (treasury active)\",\n\t\ttx: \"0300000001000000000000000000000000000000000000000000000000000000\" +\n\t\t\t\"0000000000ffffffff00ffffffff02000000000000000000000e6a0c20000000\" +\n\t\t\t\"93c1b2181e4cd3b100ac23fc0600000000001976a91423d4150eb4332733b5bf\" +\n\t\t\t\"88e5d9cea3897bc09dbc88ac00000000000000000100ac23fc06000000000000\" +\n\t\t\t\"00ffffffff0800002f646372642f\",\n\t\twantPreTrsy: true,\n\t\twantPostTrsy: true,\n\t}, {\n\t\tname: \"modified simnet block 32 coinbase (treasury active): no miner payout\",\n\t\ttx: \"030000000100000000000000000000000000000000000000000000000000000\" +\n\t\t\t\"00000000000ffffffff00ffffffff01000000000000000000000e6a0c200000\" +\n\t\t\t\"0093c1b2181e4cd3b100000000000000000100ac23fc0600000000000000fff\" +\n\t\t\t\"fffff0800002f646372642f\",\n\t\twantPreTrsy: true,\n\t\twantPostTrsy: true,\n\t}, {\n\t\tname: \"random simnet treasury spend\",\n\t\ttx: \"030000000100000000000000000000000000000000000000000000000000000\" +\n\t\t\t\"00000000000ffffffff00ffffffff0200000000000000000000226a20b63c13\" +\n\t\t\t\"400000000045c279dd8870eff33bc219a4c9a39a9190960601d8fccdefc0321\" +\n\t\t\t\"3400000000000001ac376a914c945ac8cdbf5e37ad4bfde5dc92f65e13ff5c6\" +\n\t\t\t\"7488ac000000008201000001b63c13400000000000000000ffffffff6440650\" +\n\t\t\t\"063174184d0438b26d05a2f6d3190d020994ef3c18ac110bf70df3d1ed7066c\" +\n\t\t\t\"8c62c349b8ae86862d04ee94d2bddc42bd33d449c1ba53ed37a2c8d1e8f8f62\" +\n\t\t\t\"102a36b785d584555696b69d1b2bbeff4010332b301e3edd316d79438554cac\" +\n\t\t\t\"b3e7c2\",\n\t\twantPreTrsy: true,\n\t\twantPostTrsy: false,\n\t}, {\n\t\t// This is neither a valid coinbase nor a valid treasury spend, but\n\t\t// since the coinbase identification function is only a fast heuristic,\n\t\t// this is crafted to test that.\n\t\tname: \"modified random simnet treasury spend: missing signature script\",\n\t\ttx: \"0300000001000000000000000000000000000000000000000000000000000000\" +\n\t\t\t\"0000000000ffffffff00ffffffff0200000000000000000000226a20b63c1340\" +\n\t\t\t\"0000000045c279dd8870eff33bc219a4c9a39a9190960601d8fccdefc0321340\" +\n\t\t\t\"0000000000001ac376a914c945ac8cdbf5e37ad4bfde5dc92f65e13ff5c67488\" +\n\t\t\t\"ac000000008201000001b63c13400000000000000000ffffffff00\",\n\t\twantPreTrsy: true,\n\t\twantPostTrsy: true,\n\t}}\n\n\tfor _, test := range tests {\n\t\ttxBytes, err := hex.DecodeString(test.tx)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"%q: unexpected err parsing tx hex %q: %v\", test.name,\n\t\t\t\ttest.tx, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tvar tx wire.MsgTx\n\t\tif err := tx.FromBytes(txBytes); err != nil {\n\t\t\tt.Errorf(\"%q: unexpected err parsing tx: %v\", test.name, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tresult := IsCoinBaseTx(&tx, noTreasury)\n\t\tif result != test.wantPreTrsy {\n\t\t\tt.Errorf(\"%s: unexpected result pre treasury -- got %v, want %v\",\n\t\t\t\ttest.name, result, test.wantPreTrsy)\n\t\t\tcontinue\n\t\t}\n\n\t\tresult = IsCoinBaseTx(&tx, withTreasury)\n\t\tif result != test.wantPostTrsy {\n\t\t\tt.Errorf(\"%s: unexpected result post treasury -- got %v, want %v\",\n\t\t\t\ttest.name, result, test.wantPostTrsy)\n\t\t\tcontinue\n\t\t}\n\t}\n}", "func eq(o1, o2 interface{}) bool {\n\n\tf1, ok1 := ToFloat(o1)\n\tf2, ok2 := ToFloat(o2)\n\tif ok1 && ok2 {\n\t\treturn f1 == f2\n\t}\n\n\tb1, ok1 := ToBool(o1)\n\tb2, ok1 := ToBool(o2)\n\tif ok1 && ok2 {\n\t\treturn b1 == b2\n\t}\n\n\treturn o1 == o2\n}", "func (in *CiliumLoadBalancerIPPoolSpec) DeepEqual(other *CiliumLoadBalancerIPPoolSpec) bool {\n\tif other == nil {\n\t\treturn false\n\t}\n\n\tif (in.ServiceSelector == nil) != (other.ServiceSelector == nil) {\n\t\treturn false\n\t} else if in.ServiceSelector != nil {\n\t\tif !in.ServiceSelector.DeepEqual(other.ServiceSelector) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif ((in.Cidrs != nil) && (other.Cidrs != nil)) || ((in.Cidrs == nil) != (other.Cidrs == nil)) {\n\t\tin, other := &in.Cidrs, &other.Cidrs\n\t\tif other == nil {\n\t\t\treturn false\n\t\t}\n\n\t\tif len(*in) != len(*other) {\n\t\t\treturn false\n\t\t} else {\n\t\t\tfor i, inElement := range *in {\n\t\t\t\tif !inElement.DeepEqual(&(*other)[i]) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif in.Disabled != other.Disabled {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (c clock) equals(other clock) bool {\n\treturn reflect.DeepEqual(c, other)\n}", "func equal(a, b float64) bool {\n\treturn math.Abs(a-b) <= equalityThreshold\n}", "func (in *CiliumBGPVirtualRouter) DeepEqual(other *CiliumBGPVirtualRouter) bool {\n\tif other == nil {\n\t\treturn false\n\t}\n\n\tif in.LocalASN != other.LocalASN {\n\t\treturn false\n\t}\n\tif (in.ExportPodCIDR == nil) != (other.ExportPodCIDR == nil) {\n\t\treturn false\n\t} else if in.ExportPodCIDR != nil {\n\t\tif *in.ExportPodCIDR != *other.ExportPodCIDR {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif (in.ServiceSelector == nil) != (other.ServiceSelector == nil) {\n\t\treturn false\n\t} else if in.ServiceSelector != nil {\n\t\tif !in.ServiceSelector.DeepEqual(other.ServiceSelector) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif ((in.Neighbors != nil) && (other.Neighbors != nil)) || ((in.Neighbors == nil) != (other.Neighbors == nil)) {\n\t\tin, other := &in.Neighbors, &other.Neighbors\n\t\tif other == nil {\n\t\t\treturn false\n\t\t}\n\n\t\tif len(*in) != len(*other) {\n\t\t\treturn false\n\t\t} else {\n\t\t\tfor i, inElement := range *in {\n\t\t\t\tif !inElement.DeepEqual(&(*other)[i]) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true\n}", "func (d BigDecimal) Equal(ref BigDecimal) bool {\n\tif d.Cmp(ref) != 0 {\n\t\treturn false\n\t}\n\treturn true\n}", "func (GoVersion) Eq(version string) bool { return boolResult }", "func (v Vect) Equals(other Vect) bool {\n\treturn int(C.cpveql(toC(v), toC(other))) == 1\n}", "func HasStableCoin(PublicKey string) bool {\n\taccount, err := TestNetClient.LoadAccount(PublicKey)\n\tif err != nil {\n\t\t// account does not exist\n\t\treturn false\n\t}\n\n\tfor _, balance := range account.Balances {\n\t\tif balance.Asset.Code == \"STABLEUSD\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func equal(z1, z2 *big.Int) bool {\n\treturn z1.Cmp(z2) == 0\n}", "func FlipCoin(p float64) bool {\n\tif p == 1.0 {\n\t\treturn true\n\t}\n\tif p == 0.0 {\n\t\treturn false\n\t}\n\tif rand.Float64() <= p {\n\t\treturn true\n\t}\n\treturn false\n}", "func (a *Asserter) BalanceEq(addr address.Address, expected abi.TokenAmount) {\n\tst := a.suppliers.stateTracker()\n\tactor, err := st.StateTree.GetActor(addr)\n\ta.NoError(err, \"failed to fetch actor %s from state\", addr)\n\ta.Equal(expected, actor.Balance, \"balances mismatch for address %s\", addr)\n}", "func (d Decimal) Equals(d2 Decimal) bool {\n\treturn d.Equal(d2)\n}", "func (d Decimal) Equals(d2 Decimal) bool {\n\treturn d.Equal(d2)\n}", "func (coin Coin) IsZero() bool {\n\treturn coin.Amount.Sign() == 0\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 (p Point) Eq(q Point) bool {\n\treturn p == q\n}", "func (in *CiliumBGPNeighbor) DeepEqual(other *CiliumBGPNeighbor) bool {\n\tif other == nil {\n\t\treturn false\n\t}\n\n\tif in.PeerAddress != other.PeerAddress {\n\t\treturn false\n\t}\n\tif (in.PeerPort == nil) != (other.PeerPort == nil) {\n\t\treturn false\n\t} else if in.PeerPort != nil {\n\t\tif *in.PeerPort != *other.PeerPort {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif in.PeerASN != other.PeerASN {\n\t\treturn false\n\t}\n\tif (in.EBGPMultihopTTL == nil) != (other.EBGPMultihopTTL == nil) {\n\t\treturn false\n\t} else if in.EBGPMultihopTTL != nil {\n\t\tif *in.EBGPMultihopTTL != *other.EBGPMultihopTTL {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif (in.ConnectRetryTimeSeconds == nil) != (other.ConnectRetryTimeSeconds == nil) {\n\t\treturn false\n\t} else if in.ConnectRetryTimeSeconds != nil {\n\t\tif *in.ConnectRetryTimeSeconds != *other.ConnectRetryTimeSeconds {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif (in.HoldTimeSeconds == nil) != (other.HoldTimeSeconds == nil) {\n\t\treturn false\n\t} else if in.HoldTimeSeconds != nil {\n\t\tif *in.HoldTimeSeconds != *other.HoldTimeSeconds {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif (in.KeepAliveTimeSeconds == nil) != (other.KeepAliveTimeSeconds == nil) {\n\t\treturn false\n\t} else if in.KeepAliveTimeSeconds != nil {\n\t\tif *in.KeepAliveTimeSeconds != *other.KeepAliveTimeSeconds {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif (in.GracefulRestart == nil) != (other.GracefulRestart == nil) {\n\t\treturn false\n\t} else if in.GracefulRestart != nil {\n\t\tif !in.GracefulRestart.DeepEqual(other.GracefulRestart) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif ((in.Families != nil) && (other.Families != nil)) || ((in.Families == nil) != (other.Families == nil)) {\n\t\tin, other := &in.Families, &other.Families\n\t\tif other == nil {\n\t\t\treturn false\n\t\t}\n\n\t\tif len(*in) != len(*other) {\n\t\t\treturn false\n\t\t} else {\n\t\t\tfor i, inElement := range *in {\n\t\t\t\tif !inElement.DeepEqual(&(*other)[i]) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true\n}", "func Equals(a, b interface{}) bool {\n\treturn neogointernal.Opcode2(\"EQUAL\", a, b).(bool)\n}", "func EqFn(a interface{}, b interface{}) bool {\n\treturn a == b\n}", "func Eq(f1, f2 Formula) Formula {\n\treturn and{or{not{f1}, f2}, or{f1, not{f2}}}\n}", "func TestPriceCompareInverse(t *testing.T) {\n\tnormalPrice := &Price{\n\t\tAmountWant: uint64(505763),\n\t\tAmountHave: uint64(37049),\n\t}\n\tinversePrice := &Price{\n\t\tAmountWant: uint64(37049),\n\t\tAmountHave: uint64(505763),\n\t}\n\n\tif leftSide := normalPrice.Cmp(inversePrice); leftSide != 1 {\n\t\tt.Errorf(\"A price that is greater than 1 should not be less than or equal to its inverse\")\n\t\treturn\n\t}\n\tif rightSide := inversePrice.Cmp(normalPrice); rightSide != -1 {\n\t\tt.Errorf(\"The inverse of a price greater than 1 should not be greater than or equal to the original price\")\n\t\treturn\n\t}\n\treturn\n}", "func (v Peer) Equal(o Peer) bool {\n\treturn string(v.Metadata) == string(o.Metadata) &&\n\t\tv.PeerID == o.PeerID\n}", "func (s *Struct) Eq(rhs interface{}) bool {\n\treturn s == rhs || eqMapLike(s, rhs)\n}", "func (oc *ObjectComprehension) Equal(other Value) bool {\n\treturn Compare(oc, other) == 0\n}", "func eq128(a0, a1, b0, b1 uint64) bool {\n\treturn (a0 == b0) && (a1 == b1)\n}", "func (v ConstructionHashRequest) Equal(o ConstructionHashRequest) bool {\n\treturn v.SignedTransaction == o.SignedTransaction\n}", "func (recv *ObjectConstructParam) Equals(other *ObjectConstructParam) bool {\n\treturn other.ToC() == recv.ToC()\n}", "func (v Amount) Equal(o Amount) bool {\n\treturn v.Currency.Equal(o.Currency) &&\n\t\tstring(v.Metadata) == string(o.Metadata) &&\n\t\tv.Value == o.Value\n}", "func (utxo ExtBtcCompatUTXO) Equal(other Value) bool {\n\totherUTXO, ok := other.(ExtBtcCompatUTXO)\n\tif !ok {\n\t\treturn false\n\t}\n\treturn utxo.TxHash.Equal(otherUTXO.TxHash) &&\n\t\tutxo.VOut.Equal(otherUTXO.VOut) &&\n\t\tutxo.ScriptPubKey.Equal(otherUTXO.ScriptPubKey) &&\n\t\tutxo.Amount.Equal(otherUTXO.Amount) &&\n\t\tutxo.GHash.Equal(otherUTXO.GHash)\n}", "func WriteCoin(slug string, v interface{}, d interface{}) bool {\n\tdc := mod.Cache{Data: d}\n\treturn DB.Write(cfg.Web+\"/coins\", slug, v) == nil &&\n\t\tDB.Write(cfg.Web+\"/data/\"+slug, \"info\", dc) == nil\n}", "func StatesEq(a *State, b *State) bool {\n\treturn reflect.DeepEqual(a, b)\n}", "func (in *CoreCiliumEndpoint) DeepEqual(other *CoreCiliumEndpoint) bool {\n\tif other == nil {\n\t\treturn false\n\t}\n\n\tif in.Name != other.Name {\n\t\treturn false\n\t}\n\tif in.IdentityID != other.IdentityID {\n\t\treturn false\n\t}\n\tif (in.Networking == nil) != (other.Networking == nil) {\n\t\treturn false\n\t} else if in.Networking != nil {\n\t\tif !in.Networking.DeepEqual(other.Networking) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif in.Encryption != other.Encryption {\n\t\treturn false\n\t}\n\n\tif ((in.NamedPorts != nil) && (other.NamedPorts != nil)) || ((in.NamedPorts == nil) != (other.NamedPorts == nil)) {\n\t\tin, other := &in.NamedPorts, &other.NamedPorts\n\t\tif other == nil {\n\t\t\treturn false\n\t\t}\n\n\t\tif len(*in) != len(*other) {\n\t\t\treturn false\n\t\t} else {\n\t\t\tfor i, inElement := range *in {\n\t\t\t\tif !inElement.DeepEqual((*other)[i]) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true\n}", "func (in *CoreCiliumEndpoint) DeepEqual(other *CoreCiliumEndpoint) bool {\n\tif other == nil {\n\t\treturn false\n\t}\n\n\tif in.Name != other.Name {\n\t\treturn false\n\t}\n\tif in.IdentityID != other.IdentityID {\n\t\treturn false\n\t}\n\tif (in.Networking == nil) != (other.Networking == nil) {\n\t\treturn false\n\t} else if in.Networking != nil {\n\t\tif !in.Networking.DeepEqual(other.Networking) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif in.Encryption != other.Encryption {\n\t\treturn false\n\t}\n\n\tif ((in.NamedPorts != nil) && (other.NamedPorts != nil)) || ((in.NamedPorts == nil) != (other.NamedPorts == nil)) {\n\t\tin, other := &in.NamedPorts, &other.NamedPorts\n\t\tif other == nil || !in.DeepEqual(other) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (recv *ParamSpecUInt) Equals(other *ParamSpecUInt) bool {\n\treturn other.ToC() == recv.ToC()\n}", "func (in *IPPoolSpec) DeepEqual(other *IPPoolSpec) bool {\n\tif other == nil {\n\t\treturn false\n\t}\n\n\tif (in.IPv4 == nil) != (other.IPv4 == nil) {\n\t\treturn false\n\t} else if in.IPv4 != nil {\n\t\tif !in.IPv4.DeepEqual(other.IPv4) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif (in.IPv6 == nil) != (other.IPv6 == nil) {\n\t\treturn false\n\t} else if in.IPv6 != nil {\n\t\tif !in.IPv6.DeepEqual(other.IPv6) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (recv *ParamSpecPool) Equals(other *ParamSpecPool) bool {\n\treturn other.ToC() == recv.ToC()\n}", "func (tx ExtEthCompatTx) Equal(other Value) bool {\n\totherTx, ok := other.(ExtEthCompatTx)\n\tif !ok {\n\t\treturn false\n\t}\n\treturn tx.TxHash.Equal(otherTx.TxHash)\n}", "func (w *Wallet) Equal(z *Wallet) bool {\n\tif w != nil && z != nil {\n\t\treturn w.Currency == z.Currency && w.Balance == z.Balance && w.Sequence == z.Sequence\n\t}\n\treturn w == z\n}", "func (coins DecCoins) IsValid() bool {\n\tswitch len(coins) {\n\tcase 0:\n\t\treturn true\n\n\tcase 1:\n\t\tif err := validateDenom(coins[0].Denom); err != nil {\n\t\t\treturn false\n\t\t}\n\t\treturn coins[0].IsPositive()\n\n\tdefault:\n\t\t// check single coin case\n\t\tif !(DecCoins{coins[0]}).IsValid() {\n\t\t\treturn false\n\t\t}\n\n\t\tlowDenom := coins[0].Denom\n\t\tfor _, coin := range coins[1:] {\n\t\t\tif strings.ToLower(coin.Denom) != coin.Denom {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tif coin.Denom <= lowDenom {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tif !coin.IsPositive() {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\t// we compare each coin against the last denom\n\t\t\tlowDenom = coin.Denom\n\t\t}\n\n\t\treturn true\n\t}\n}", "func (c *Credentials) Equal(other *Credentials) bool {\n\treturn c != nil &&\n\t\tother != nil &&\n\t\tc.Key == other.Key &&\n\t\tc.ClientID == other.ClientID &&\n\t\t(c.SubAccount == other.SubAccount || c.SubAccount == \"\" && other.SubAccount == \"main\" || c.SubAccount == \"main\" && other.SubAccount == \"\")\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 (ip1 IP6u128) Eq(ip2 IP6u128) bool {\n\treturn ip1.Cmp(ip2) == 0\n}", "func (recv *ParamSpecUInt64) Equals(other *ParamSpecUInt64) bool {\n\treturn other.ToC() == recv.ToC()\n}", "func (m Money) Cmp(other Money) (int, error) {\n\tif !m.currency.Equals(other.currency) {\n\t\treturn 0, &ErrDifferentCurrency{m.currency, other.currency}\n\t}\n\treturn m.amount.Cmp(other.amount), nil\n}", "func eq(args ...interface{}) bool {\n\tif len(args) == 0 {\n\t\treturn false\n\t}\n\tx := args[0]\n\tswitch x := x.(type) {\n\tcase string, int, int64, byte, float32, float64:\n\t\tfor _, y := range args[1:] {\n\t\t\tif x == y {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\tfor _, y := range args[1:] {\n\t\tif reflect.DeepEqual(x, y) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func eq(args ...interface{}) bool {\n\tif len(args) == 0 {\n\t\treturn false\n\t}\n\tx := args[0]\n\tswitch x := x.(type) {\n\tcase string, int, int64, byte, float32, float64:\n\t\tfor _, y := range args[1:] {\n\t\t\tif x == y {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\tfor _, y := range args[1:] {\n\t\tif reflect.DeepEqual(x, y) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (c *Candidate) Equal(b *Candidate) bool {\n\tif !c.ConnectionAddress.Equal(b.ConnectionAddress) {\n\t\treturn false\n\t}\n\tif c.Port != b.Port {\n\t\treturn false\n\t}\n\tif c.Transport != b.Transport {\n\t\treturn false\n\t}\n\tif !bytes.Equal(c.TransportValue, b.TransportValue) {\n\t\treturn false\n\t}\n\tif c.Foundation != b.Foundation {\n\t\treturn false\n\t}\n\tif c.ComponentID != b.ComponentID {\n\t\treturn false\n\t}\n\tif c.Priority != b.Priority {\n\t\treturn false\n\t}\n\tif c.Type != b.Type {\n\t\treturn false\n\t}\n\tif c.NetworkCost != b.NetworkCost {\n\t\treturn false\n\t}\n\tif c.Generation != b.Generation {\n\t\treturn false\n\t}\n\tif !c.Attributes.Equal(b.Attributes) {\n\t\treturn false\n\t}\n\treturn true\n}", "func (e *ConstantExpr) Eq(other *ConstantExpr) *ConstantExpr {\n\tassert(e.Width == other.Width, \"eq: width mismatch: %d != %d\", e.Width, other.Width)\n\tif e.Value == other.Value {\n\t\treturn NewConstantExpr(1, WidthBool)\n\t}\n\treturn NewConstantExpr(0, WidthBool)\n}", "func (ref Ref) Equal(other Value) bool {\n\treturn Compare(ref, other) == 0\n}" ]
[ "0.70465946", "0.6923523", "0.60608363", "0.60347974", "0.6028179", "0.60094017", "0.5901305", "0.58853287", "0.58778554", "0.5840299", "0.58085173", "0.5762222", "0.5661418", "0.5580482", "0.5563641", "0.5520213", "0.54485756", "0.5405266", "0.54030937", "0.5394832", "0.53687775", "0.5358282", "0.5358282", "0.53297544", "0.5285027", "0.52763593", "0.5269229", "0.52658004", "0.5256752", "0.52444196", "0.52444196", "0.5241736", "0.52380437", "0.5233506", "0.5223962", "0.5217641", "0.52020293", "0.52005714", "0.51921785", "0.5171367", "0.51511294", "0.5142358", "0.5135082", "0.51301533", "0.5121962", "0.5120579", "0.5120579", "0.50980514", "0.5094809", "0.50912344", "0.50887793", "0.5087059", "0.50729936", "0.50661296", "0.50606203", "0.5051528", "0.5043822", "0.5027348", "0.5020527", "0.5012831", "0.50101197", "0.4993227", "0.49923995", "0.49923995", "0.49623585", "0.49393642", "0.4929838", "0.49195057", "0.4917329", "0.49130696", "0.49125868", "0.49090534", "0.489253", "0.48865768", "0.48839483", "0.48678032", "0.48629662", "0.48548287", "0.48536664", "0.48526335", "0.48479125", "0.48470655", "0.48448437", "0.48430103", "0.48373693", "0.4834056", "0.48332107", "0.48310193", "0.48242226", "0.48237783", "0.48121655", "0.48119923", "0.48066574", "0.4806234", "0.4802984", "0.48009723", "0.48009723", "0.47996268", "0.4798124", "0.47978717" ]
0.74850535
0
MarshalYAML returns the YAML representation of a ClawbackVestingAccount.
MarshalYAML возвращает представление YAML ClawbackVestingAccount.
func (va ClawbackVestingAccount) MarshalYAML() (interface{}, error) { accAddr, err := sdk.AccAddressFromBech32(va.Address) if err != nil { return nil, err } out := vestingAccountYAML{ Address: accAddr, AccountNumber: va.AccountNumber, PubKey: getPKString(va), Sequence: va.Sequence, OriginalVesting: va.OriginalVesting, DelegatedFree: va.DelegatedFree, DelegatedVesting: va.DelegatedVesting, EndTime: va.EndTime, StartTime: va.StartTime, VestingPeriods: va.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 (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 (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 (i Instance) MarshalYAML() (interface{}, error) {\n\treturn i.Vars, nil\n}", "func (i UserGroupAccess) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}", "func (o *OAuthFlow) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(o, o.low)\n\treturn nb.Render(), 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 (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 (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 (key PrivateKey) MarshalYAML() (interface{}, error) {\n\treturn key.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 (export WebAuthnDeviceExport) MarshalYAML() (any, error) {\n\treturn export.ToData(), nil\n}", "func (p *Parameter) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(p, p.low)\n\treturn nb.Render(), nil\n}", "func (key PublicKey) MarshalYAML() (interface{}, error) {\n\treturn key.String(), 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 ChannelName) MarshalYAML() (interface{}, error) {\n\treturn i.String(), 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 (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 (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 (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 MarshalToYaml(obj runtime.Object, gv schema.GroupVersion) ([]byte, error) {\n\treturn MarshalToYamlForCodecs(obj, gv, clientsetscheme.Codecs)\n}", "func (f Fixed8) MarshalYAML() (interface{}, error) {\n\treturn f.String(), nil\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 (s GitEvent) MarshalYAML() (interface{}, error) {\n\treturn toString[s], nil\n}", "func (m *BootstrapMode) MarshalYAML() (interface{}, error) {\n\treturn m.String(), nil\n}", "func (ep Endpoint) MarshalYAML() (interface{}, error) {\n\ts, err := ep.toString()\n\treturn s, err\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 (d Rate) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}", "func (o *OpenAPI3SchemaExtension) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}", "func (p Params) MarshalYAML() (interface{}, error) {\n\treturn p.String(), nil\n}", "func (f Flag) MarshalYAML() (interface{}, error) {\n\treturn f.Name, nil\n}", "func (op OpRetain) MarshalYAML() (interface{}, error) {\n\treturn op.Fields, 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 (b ByteCount) MarshalYAML() (interface{}, error) {\n\treturn uint64(b), 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 (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 (v *Int8) MarshalYAML() (interface{}, error) {\n\tif v.IsAssigned {\n\t\treturn v.Val, nil\n\t}\n\treturn nil, nil\n}", "func (o *OpenAPI3ResponseExtension) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}", "func (k *Kluster) YAML() ([]byte, error) {\n\treturn yaml.Marshal(k)\n}", "func (ec EllipticCurve) MarshalYAML() (interface{}, error) {\n\treturn ec.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 (d LegacyDec) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}", "func (f BodyField) MarshalYAML() (interface{}, error) {\n\treturn toJSONDot(f), nil\n}", "func (cp *CertPool) MarshalYAML() (interface{}, error) {\n\treturn cp.Files, 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 (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 (r *Regexp) MarshalYAML() (interface{}, error) {\n\treturn r.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 (o *OpenAPI3Options) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\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 (schema SchemaType) MarshalYAML() (interface{}, error) {\n\treturn schema.String(), nil\n}", "func (i UOM) MarshalYAML() (interface{}, error) {\n\treturn i.String(), 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 (c CompressionType) MarshalYAML() (interface{}, error) {\n\treturn compressionTypeID[c], 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 (d Document) MarshalYAML() (interface{}, error) {\n\treturn d.raw, nil\n}", "func (c *Config) YAML() ([]byte, error) {\n\treturn yaml.Marshal(c)\n}", "func (c Configuration) YAML() ([]byte, error) {\n\treturn yaml.Marshal(c)\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 (a *Account) Marshal() ([]byte, error) {\n\treturn a.account.Bytes()\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 (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\treturn u.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 (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 (cfg frozenConfig) MarshalIndent(val interface{}, prefix, indent string) ([]byte, error) {\n return encoder.EncodeIndented(val, prefix, indent, cfg.encoderOpts)\n}", "func (s *spiff) Marshal(node Node) ([]byte, error) {\n\treturn yaml.Marshal(node)\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 (vm ValidationMap) AsYAML() (string, error) {\n\tdata, err := yaml.Marshal(vm)\n\treturn string(data), err\n}", "func Dump(cfg interface{}, dst io.Writer) error {\n\treturn yaml.NewEncoder(dst).Encode(cfg)\n}", "func (f *Fzp) ToYAML() ([]byte, error) {\n\tdata, err := yaml.Marshal(f)\n\treturn data, err\n}", "func (c Config) ToYAML() string {\n\tdata, _ := yaml.Marshal(c)\n\treturn string(data)\n}", "func (d Duration) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}", "func Dump(v interface{}) ([]byte, error) {\n\treturn yaml.Marshal(v)\n}", "func (d Duration) MarshalYAML() (interface{}, error) {\n\treturn d.Duration.String(), 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 (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 (a Account) Save(filePath string) error {\n\td, err := yaml.Marshal(a)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = ioutil.WriteFile(filePath, d, 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\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 (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 ContainerazureAlphaClusterWorkloadIdentityConfigToProto(o *alpha.ClusterWorkloadIdentityConfig) *alphapb.ContainerazureAlphaClusterWorkloadIdentityConfig {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &alphapb.ContainerazureAlphaClusterWorkloadIdentityConfig{}\n\tp.SetIssuerUri(dcl.ValueOrEmptyString(o.IssuerUri))\n\tp.SetWorkloadPool(dcl.ValueOrEmptyString(o.WorkloadPool))\n\tp.SetIdentityProvider(dcl.ValueOrEmptyString(o.IdentityProvider))\n\treturn p\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 (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 (c *Config) Dump() ([]byte, error) {\n\tb, err := yaml.Marshal(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn b, nil\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 (acc *Account) Serialize() ([]byte, error) {\n\treturn json.Marshal(acc)\n}" ]
[ "0.81687456", "0.8013179", "0.78075606", "0.77150255", "0.63062006", "0.6222024", "0.61517715", "0.6118727", "0.60633063", "0.60269654", "0.5953029", "0.5952517", "0.5855554", "0.5855083", "0.5827823", "0.5779316", "0.5734564", "0.571303", "0.5689044", "0.5630494", "0.5589824", "0.5582469", "0.55512136", "0.5445769", "0.54448503", "0.54265296", "0.5421635", "0.5409735", "0.54024094", "0.53555834", "0.5349621", "0.534485", "0.534485", "0.5342051", "0.53394437", "0.53357315", "0.53289723", "0.53286994", "0.53280103", "0.5316041", "0.5310311", "0.5301155", "0.52899104", "0.5277522", "0.52707964", "0.52627325", "0.52564955", "0.5249496", "0.52154136", "0.521424", "0.5206155", "0.5189614", "0.51094496", "0.51094496", "0.50685984", "0.50638443", "0.50474495", "0.5035644", "0.5026148", "0.5020545", "0.49739468", "0.49523404", "0.49467063", "0.49260494", "0.49075344", "0.48836628", "0.48808745", "0.48713064", "0.48423284", "0.4828866", "0.47944242", "0.4790343", "0.4789781", "0.47636038", "0.47567108", "0.4735841", "0.47084555", "0.4693027", "0.46878573", "0.46787977", "0.4677704", "0.46720177", "0.46664992", "0.46597022", "0.46551752", "0.4646939", "0.46306318", "0.4623652", "0.46223155", "0.460824", "0.45978552", "0.4576248", "0.45351648", "0.45339996", "0.45329022", "0.4524215", "0.44933507", "0.4490635", "0.44768015", "0.44752574" ]
0.848191
0
NewClawbackGrantAction returns an AddGrantAction for a ClawbackVestingAccount.
NewClawbackGrantAction возвращает AddGrantAction для ClawbackVestingAccount.
func NewClawbackGrantAction( funderAddress string, sk StakingKeeper, grantStartTime int64, grantLockupPeriods, grantVestingPeriods []Period, grantCoins sdk.Coins, ) exported.AddGrantAction { return clawbackGrantAction{ funderAddress: funderAddress, sk: sk, grantStartTime: grantStartTime, grantLockupPeriods: grantLockupPeriods, grantVestingPeriods: grantVestingPeriods, grantCoins: grantCoins, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewClawbackAction(requestor, dest sdk.AccAddress, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) exported.ClawbackAction {\n\treturn clawbackAction{\n\t\trequestor: requestor,\n\t\tdest: dest,\n\t\tak: ak,\n\t\tbk: bk,\n\t\tsk: sk,\n\t}\n}", "func NewClawbackRewardAction(ak AccountKeeper, bk BankKeeper, sk StakingKeeper) exported.RewardAction {\n\treturn clawbackRewardAction{\n\t\tak: ak,\n\t\tbk: bk,\n\t\tsk: sk,\n\t}\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 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 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 (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 NewCollateralizeAction(c *Collateralize, tx *types.Transaction, index int) *Action {\n\thash := tx.Hash()\n\tfromaddr := tx.From()\n\tcfg := c.GetAPI().GetConfig()\n\ttokenDb, err := account.NewAccountDB(cfg, tokenE.GetName(), pty.CCNYTokenName, c.GetStateDB())\n\tif err != nil {\n\t\tclog.Error(\"NewCollateralizeAction\", \"Get Account DB error\", \"error\", err)\n\t\treturn nil\n\t}\n\n\treturn &Action{\n\t\tcoinsAccount: c.GetCoinsAccount(), tokenAccount: tokenDb, db: c.GetStateDB(), localDB: c.GetLocalDB(),\n\t\ttxhash: hash, fromaddr: fromaddr, blocktime: c.GetBlockTime(), height: c.GetHeight(),\n\t\texecaddr: dapp.ExecAddress(string(tx.Execer)), difficulty: c.GetDifficulty(), index: index, Collateralize: c}\n}", "func (pva *PeriodicVestingAccount) AddGrant(ctx sdk.Context, action exported.AddGrantAction) error {\n\treturn action.AddToAccount(ctx, pva)\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 (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 (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 NewAuthorizeAction(ctx context.Context, viper *viper.Viper, authMode string,\n\tlocalAuthController *local.Controller, bkiamAuthController *bkiam.Controller,\n\treq *pb.AuthorizeReq, resp *pb.AuthorizeResp) *AuthorizeAction {\n\n\taction := &AuthorizeAction{\n\t\tctx: ctx,\n\t\tviper: viper,\n\t\tauthMode: authMode,\n\t\tlocalAuthController: localAuthController,\n\t\tbkiamAuthController: bkiamAuthController,\n\t\treq: req,\n\t\tresp: resp,\n\t}\n\n\taction.resp.Seq = req.Seq\n\taction.resp.Code = pbcommon.ErrCode_E_OK\n\taction.resp.Message = \"OK\"\n\n\treturn action\n}", "func NewChallengeAction(msg *Message) (*ChallengeAction, error) {\n\taction := &ChallengeAction{*msg}\n\n\treturn action, nil\n}", "func CreateAction(\n\tcmd, keyB, id, secretKey string,\n\targs ...interface{}) *types.Action {\n\n\tmac := hmac.New(sha1.New, []byte(secretKey))\n\tmac.Write([]byte(cmd))\n\tmac.Write([]byte(keyB))\n\tmac.Write([]byte(id))\n\tsum := mac.Sum(nil)\n\tsumhex := hex.EncodeToString(sum)\n\n\treturn &types.Action{\n\t\tCommand: cmd,\n\t\tStorageKey: keyB,\n\t\tArgs: args,\n\t\tId: id,\n\t\tSecret: sumhex,\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 NewAction(name string, arg interface{}) {\n\tDefaultActionRegistry.Post(name, arg)\n}", "func AccountGrant() GrantBuilder {\n\treturn &CurrentGrantBuilder{\n\t\tgrantType: accountType,\n\t}\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 CreateAction(r *Raptor) *Action {\n\treturn &Action{\n\t\tRaptor: r,\n\t}\n}", "func (va *ClawbackVestingAccount) clawback(ctx sdk.Context, dest sdk.AccAddress, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) error {\n\t// Compute the clawback based on the account state only, and update account\n\ttoClawBack := va.computeClawback(ctx.BlockTime().Unix())\n\tif toClawBack.IsZero() {\n\t\treturn nil\n\t}\n\taddr := va.GetAddress()\n\tbondDenom := sk.BondDenom(ctx)\n\n\t// Compute the clawback based on bank balance and delegation, and update account\n\tencumbered := va.GetVestingCoins(ctx.BlockTime())\n\tbondedAmt := sk.GetDelegatorBonded(ctx, addr)\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, addr)\n\tbonded := sdk.NewCoins(sdk.NewCoin(bondDenom, bondedAmt))\n\tunbonding := sdk.NewCoins(sdk.NewCoin(bondDenom, unbondingAmt))\n\tunbonded := bk.GetAllBalances(ctx, addr)\n\ttoClawBack = va.updateDelegation(encumbered, toClawBack, bonded, unbonding, unbonded)\n\n\t// Write now now so that the bank module sees unvested tokens are unlocked.\n\t// Note that all store writes are aborted if there is a panic, so there is\n\t// no danger in writing incomplete results.\n\tak.SetAccount(ctx, va)\n\n\t// Now that future vesting events (and associated lockup) are removed,\n\t// the balance of the account is unlocked and can be freely transferred.\n\tspendable := bk.SpendableCoins(ctx, addr)\n\ttoXfer := coinsMin(toClawBack, spendable)\n\terr := bk.SendCoins(ctx, addr, dest, toXfer)\n\tif err != nil {\n\t\treturn err // shouldn't happen, given spendable check\n\t}\n\ttoClawBack = toClawBack.Sub(toXfer)\n\n\t// We need to traverse the staking data structures to update the\n\t// vesting account bookkeeping, and to recover more funds if necessary.\n\t// Staking is the only way unvested tokens should be missing from the bank balance.\n\n\t// If we need more, transfer UnbondingDelegations.\n\twant := toClawBack.AmountOf(bondDenom)\n\tunbondings := sk.GetUnbondingDelegations(ctx, addr, math.MaxUint16)\n\tfor _, unbonding := range unbondings {\n\t\tvalAddr, err := sdk.ValAddressFromBech32(unbonding.ValidatorAddress)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\ttransferred := sk.TransferUnbonding(ctx, addr, dest, valAddr, want)\n\t\twant = want.Sub(transferred)\n\t\tif !want.IsPositive() {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// If we need more, transfer Delegations.\n\tif want.IsPositive() {\n\t\tdelegations := sk.GetDelegatorDelegations(ctx, addr, math.MaxUint16)\n\t\tfor _, delegation := range delegations {\n\t\t\tvalidatorAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err) // shouldn't happen\n\t\t\t}\n\t\t\tvalidator, found := sk.GetValidator(ctx, validatorAddr)\n\t\t\tif !found {\n\t\t\t\t// validator has been removed\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\twantShares, err := validator.SharesFromTokensTruncated(want)\n\t\t\tif err != nil {\n\t\t\t\t// validator has no tokens\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttransferredShares := sk.TransferDelegation(ctx, addr, dest, delegation.GetValidatorAddr(), wantShares)\n\t\t\t// to be conservative in what we're clawing back, round transferred shares up\n\t\t\ttransferred := validator.TokensFromSharesRoundUp(transferredShares).RoundInt()\n\t\t\twant = want.Sub(transferred)\n\t\t\tif !want.IsPositive() {\n\t\t\t\t// Could be slightly negative, due to rounding?\n\t\t\t\t// Don't think so, due to the precautions above.\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// If we've transferred everything and still haven't transferred the desired clawback amount,\n\t// then the account must have most some unvested tokens from slashing.\n\treturn nil\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 AddActionAction(c *gin.Context) {\n\tresult := render.NewResult()\n\tdefer c.JSON(http.StatusOK, result)\n\n\taction := &model.Action{}\n\tif err := c.BindJSON(action); nil != err {\n\t\tresult.Error(err)\n\n\t\treturn\n\t}\n\n\tsrv := service.FromContext(c)\n\tif err := srv.Actions.Create(c, action); nil != err {\n\t\tresult.Error(err)\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 NewCreateGoalController(cgtRepos *persistence.Services, logger *log.Logger, authorizationService authorization.JwtService) Controller {\n\tcreateGoalUsecase := usecase.NewCreateGoalUsecase(&cgtRepos.Achiever, &cgtRepos.Goal, authorizationService)\n\n\tctrl := &createGoalController{\n\t\tUsecase: createGoalUsecase,\n\t\tLogger: logger,\n\t\tAuthorization: authorizationService,\n\t}\n\treturn ctrl\n}", "func (qiu *QueueItemUpdate) AddAction(i int) *QueueItemUpdate {\n\tqiu.mutation.AddAction(i)\n\treturn qiu\n}", "func NewRollbackAction(kit kit.Kit, viper *viper.Viper,\n\tauthSvrCli pbauthserver.AuthClient, dataMgrCli pbdatamanager.DataManagerClient,\n\tgseControllerCli pbgsecontroller.GSEControllerClient,\n\treq *pb.RollbackReleaseReq, resp *pb.RollbackReleaseResp) *RollbackAction {\n\n\taction := &RollbackAction{\n\t\tkit: kit,\n\t\tviper: viper,\n\t\tauthSvrCli: authSvrCli,\n\t\tdataMgrCli: dataMgrCli,\n\t\tgseControllerCli: gseControllerCli,\n\t\treq: req,\n\t\tresp: resp,\n\t}\n\n\taction.resp.Result = true\n\taction.resp.Code = pbcommon.ErrCode_E_OK\n\taction.resp.Message = \"OK\"\n\n\treturn action\n}", "func (c *ContractBackend) NewTransactor(ctx context.Context, gasLimit uint64,\n\tacc accounts.Account) (*bind.TransactOpts, error) {\n\tc.nonceMtx.Lock()\n\tdefer c.nonceMtx.Unlock()\n\texpectedNextNonce, found := c.expectedNextNonce[acc.Address]\n\tif !found {\n\t\tc.expectedNextNonce[acc.Address] = 0\n\t}\n\n\tauth, err := c.tr.NewTransactor(acc)\n\tif err != nil {\n\t\treturn nil, errors.WithMessage(err, \"creating transactor\")\n\t}\n\n\tauth.GasLimit = gasLimit\n\tauth.Context = ctx\n\n\tnonce, err := c.PendingNonceAt(ctx, acc.Address)\n\tif err != nil {\n\t\terr = cherrors.CheckIsChainNotReachableError(err)\n\t\treturn nil, errors.WithMessage(err, \"fetching nonce\")\n\t}\n\tif nonce < expectedNextNonce {\n\t\tnonce = expectedNextNonce\n\t}\n\n\tauth.Nonce = big.NewInt(int64(nonce))\n\tc.expectedNextNonce[acc.Address] = nonce + 1\n\n\treturn auth, nil\n}", "func NewBcBotAction(j *bot.Jobs) *BcBotAction {\n\t// client := resty.New()\n\t// client.\n\t// \tSetRetryCount(3).\n\t// \tSetRetryWaitTime(10 * time.Second)\n\treturn &BcBotAction{jobs: j, client: nil, mutex: new(sync.RWMutex)}\n}", "func (qiuo *QueueItemUpdateOne) AddAction(i int) *QueueItemUpdateOne {\n\tqiuo.mutation.AddAction(i)\n\treturn qiuo\n}", "func NewRecoverableAction(supervisor *Supervisor) *RecoverableAction {\n\tra := &RecoverableAction{\n\t\tactionChan: make(chan Action),\n\t\treplyChan: make(chan string, 5),\n\t\tsupervisor: supervisor,\n\t}\n\n\tra.heartbeat = NewHeartbeat(ra, 1e8)\n\n\tgo ra.backend()\n\n\treturn ra\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 NewGrantCheck(check GrantChecker, handler GrantHandler, errorHandler GrantErrorHandler) osinserver.AuthorizeHandler {\n\treturn &GrantCheck{check, handler, errorHandler}\n}", "func NewAccessControl(address common.Address, backend bind.ContractBackend) (*AccessControl, error) {\n\tcontract, err := bindAccessControl(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &AccessControl{AccessControlCaller: AccessControlCaller{contract: contract}, AccessControlTransactor: AccessControlTransactor{contract: contract}, AccessControlFilterer: AccessControlFilterer{contract: contract}}, nil\n}", "func NewAccessControl(address common.Address, backend bind.ContractBackend) (*AccessControl, error) {\n\tcontract, err := bindAccessControl(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &AccessControl{AccessControlCaller: AccessControlCaller{contract: contract}, AccessControlTransactor: AccessControlTransactor{contract: contract}, AccessControlFilterer: AccessControlFilterer{contract: contract}}, nil\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 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 NewRedirectGrant(url string) GrantHandler {\n\treturn &redirectGrant{url}\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 NewShowAction() *ShowAction {\n\treturn &ShowAction{}\n}", "func CreateBackupAction(service *pgCommon.PostgresServiceInformations) action.IAction {\n\treturn action.FormAction{\n\t\tName: \"Backup\",\n\t\tUniqueCommand: \"cmd_pg_create_backup\",\n\t\tPlaceholder: nil,\n\t\tActionExecuteCallback: func(placeholder interface{}) (interface{}, error) {\n\t\t\treturn nil, CreateBackup(service)\n\t\t},\n\t}\n}", "func NewAction(t *Pos33Ticket, tx *types.Transaction) *Action {\n\thash := tx.Hash()\n\tfromaddr := tx.From()\n\treturn &Action{t.GetCoinsAccount(), t.GetStateDB(), hash, fromaddr,\n\t\tt.GetBlockTime(), t.GetHeight(), dapp.ExecAddress(string(tx.Execer)), t.GetAPI()}\n}", "func NewAction() actions.Action {\n\treturn &Action{}\n}", "func NewAction() actions.Action {\n\treturn &Action{}\n}", "func NewAutoGrant() GrantHandler {\n\treturn &autoGrant{}\n}", "func (n *noopRules) Grant(rule *Rule) error {\n\treturn nil\n}", "func NewAction() actions.Action {\n\treturn &action{}\n}", "func CreateAction(action func(*cli.Context) error) func(*cli.Context) error {\n\treturn func(c *cli.Context) error {\n\t\terr := action(c)\n\t\tif err != nil {\n\t\t\tiocli.Error(\"%s\", err)\n\t\t}\n\n\t\treturn nil\n\t}\n}", "func NewBaseAccessWalletFactoryTransactor(address common.Address, transactor bind.ContractTransactor) (*BaseAccessWalletFactoryTransactor, error) {\n\tcontract, err := bindBaseAccessWalletFactory(address, nil, transactor, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &BaseAccessWalletFactoryTransactor{contract: contract}, nil\n}", "func (_BaseAccessWalletFactory *BaseAccessWalletFactoryTransactor) CreateAccessWallet(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _BaseAccessWalletFactory.contract.Transact(opts, \"createAccessWallet\")\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 (_BaseContentSpace *BaseContentSpaceTransactor) CreateAccessWallet(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _BaseContentSpace.contract.Transact(opts, \"createAccessWallet\")\n}", "func New() Action {\n\treturn &action{}\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 (pr *replica) addAction(act action) {\n\tif err := pr.actions.Put(act); err != nil {\n\t\treturn\n\t}\n\tpr.notifyWorker()\n}", "func NewAction(payload interface{}) Action {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Error: %v\\n\", r)\n\t\t\tfmt.Fprintf(os.Stderr, \"Payload: %v\\n\", payload)\n\t\t}\n\t}()\n\n\tvar a Action\n\ta.payload = payload\n\ta.headers = make(map[string]string)\n\n\tfor k, v := range payload.(map[interface{}]interface{}) {\n\t\tswitch k {\n\t\tcase \"catch\":\n\t\t\ta.catch = v.(string)\n\t\tcase \"warnings\":\n\t\t\t// TODO\n\t\t\tcontinue\n\t\tcase \"allowed_warnings\":\n\t\t\t// TODO\n\t\t\tcontinue\n\t\tcase \"node_selector\":\n\t\t\tcontinue\n\t\tcase \"headers\":\n\t\t\tfor kk, vv := range v.(map[interface{}]interface{}) {\n\t\t\t\ta.headers[kk.(string)] = vv.(string)\n\t\t\t}\n\t\tdefault:\n\t\t\ta.method = k.(string)\n\t\t\ta.params = v.(map[interface{}]interface{})\n\t\t}\n\t}\n\n\treturn a\n}", "func NewCheck() beekeeper.Action {\n\treturn &Check{}\n}", "func (alias *Alias) AddAction(operation, index, name string) *Alias {\n\tif alias.dict[ACTIONS] == nil {\n\t\talias.dict[ACTIONS] = []Dict{}\n\t}\n\taction := make(Dict)\n\taction[operation] = Dict{\"index\": index, \"alias\": name}\n\talias.dict[ACTIONS] = append(alias.dict[ACTIONS].([]Dict), action)\n\treturn alias\n}", "func NewAccessControlTransactor(address common.Address, transactor bind.ContractTransactor) (*AccessControlTransactor, error) {\n\tcontract, err := bindAccessControl(address, nil, transactor, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &AccessControlTransactor{contract: contract}, nil\n}", "func NewAccessControlTransactor(address common.Address, transactor bind.ContractTransactor) (*AccessControlTransactor, error) {\n\tcontract, err := bindAccessControl(address, nil, transactor, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &AccessControlTransactor{contract: contract}, nil\n}", "func (_BaseAccessControlGroup *BaseAccessControlGroupTransactor) GrantAccess(opts *bind.TransactOpts, candidate common.Address) (*types.Transaction, error) {\n\treturn _BaseAccessControlGroup.contract.Transact(opts, \"grantAccess\", candidate)\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 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 (g *projectGateway) CreateProjectAction(params project.CreateProjectParams) middleware.Responder {\n\trsp, err := g.projectClient.Create(context.TODO(), &proto.CreateRequest{\n\t\tName: params.Body.Name,\n\t\tDescription: params.Body.Description,\n\t})\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn project.NewCreateProjectInternalServerError()\n\t}\n\n\tif uint32(codes.OK) == rsp.Status {\n\t\tfmt.Println(fmt.Sprintf(\"project.client: ok. Id = %v\", rsp.Uuid))\n\t} else {\n\t\tfmt.Println(\"project.client: create fail. \")\n\t}\n\n\treadRsp, err := g.projectClient.Read(context.TODO(), &proto.ReadRequest{\n\t\tUuid: rsp.Uuid,\n\t})\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn project.NewCreateProjectInternalServerError()\n\t}\n\n\tpr := &models.Project{\n\t\tUUID: strfmt.UUID(readRsp.Project.Uuid),\n\t\tName: readRsp.Project.Name,\n\t\tDescription: readRsp.Project.Description,\n\t}\n\n\treturn project.NewCreateProjectCreated().WithPayload(pr)\n}", "func NewCreateAction(model store.ClusterManagerModel) *CreateAction {\n\treturn &CreateAction{\n\t\tmodel: model,\n\t}\n}", "func NewAction(app *buffalo.App) *Action {\n\tas := &Action{\n\t\tApp: app,\n\t\tModel: NewModel(),\n\t}\n\treturn as\n}", "func (a *Agent) startNewAction() {\n\tactionTypes := a.mind.actionTypes()\n\n\thighestValue := 0.0\n\tvar bestActionTypes []actionType\n\tfor _, t := range actionTypes {\n\t\tisActive := false\n\t\t// if we currently have an active action, we do not want to start a new action\n\t\tfor _, ac := range a.activity.activeActions {\n\t\t\tif ac.getState() == actionStateActive {\n\t\t\t\tisActive = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif isActive {\n\t\t\treturn\n\t\t}\n\n\t\t// TODO what if an action cannot be started\n\t\t// highest value is to eat an apple, but there is no apple, we should somehow start thinking\n\t\t// about how to obtain an apple\n\n\t\tv := actionTypeValue(t)\n\t\tif v >= highestValue {\n\t\t\tcanStart := true\n\t\t\tfor startCond := range t.getConditions()[actionConditionTypeStart] {\n\t\t\t\tif !startCond.isSatisfied(a) {\n\t\t\t\t\tcanStart = false\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif canStart {\n\t\t\t\tif v > highestValue {\n\t\t\t\t\thighestValue = v\n\t\t\t\t\tbestActionTypes = []actionType{}\n\t\t\t\t}\n\t\t\t\tbestActionTypes = append(bestActionTypes, t)\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(bestActionTypes) == 0 {\n\t\treturn\n\t}\n\n\tbestActionType := bestActionTypes[rand.Intn(len(bestActionTypes))]\n\tfor startCondition := range bestActionType.getConditions()[actionConditionTypeStart] {\n\t\tif !startCondition.isSatisfied(a) {\n\t\t\treturn\n\t\t}\n\t}\n\n\tnewAction := bestActionType.instantiate().(action)\n\ta.activity.activeActions = append(a.activity.activeActions, newAction)\n\ta.mind.addItem(bestActionType, 1.0)\n\n\t// add pre-action conditions for hypothesis training\n\tfor cond := range a.getConditions() {\n\t\tpreActionConditions := newAction.getType().getConditions()[actionConditionTypeObservedAtStart]\n\t\tpreActionConditions[cond] = true\n\t\tnewAction.getPreConditions()[cond] = true\n\t}\n}", "func createPayback(args []string) {\n\n\tpaybackRepo := payback.NewRepository(persistence.GetGormClient())\n\ttxnRepo := transaction.NewRepository(persistence.GetGormClient())\n\tpaybackSVC := payback.NewPaybackService(paybackRepo, txnRepo)\n\terr := paybackSVC.CreatePayback(context.Background(), args)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\treturn\n\t}\n\tfmt.Println(\"Successfully added payback\")\n}", "func NewCreateAction(kit kit.Kit, viper *viper.Viper,\n\tauthSvrCli pbauthserver.AuthClient, dataMgrCli pbdatamanager.DataManagerClient,\n\treq *pb.CreateStrategyReq, resp *pb.CreateStrategyResp) *CreateAction {\n\n\taction := &CreateAction{\n\t\tkit: kit,\n\t\tviper: viper,\n\t\tauthSvrCli: authSvrCli,\n\t\tdataMgrCli: dataMgrCli,\n\t\treq: req,\n\t\tresp: resp,\n\t}\n\n\taction.resp.Result = true\n\taction.resp.Code = pbcommon.ErrCode_E_OK\n\taction.resp.Message = \"OK\"\n\n\taction.labelsOr = []map[string]string{}\n\taction.labelsAnd = []map[string]string{}\n\n\treturn action\n}", "func NewBaseAccessWalletTransactor(address common.Address, transactor bind.ContractTransactor) (*BaseAccessWalletTransactor, error) {\n\tcontract, err := bindBaseAccessWallet(address, nil, transactor, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &BaseAccessWalletTransactor{contract: contract}, nil\n}", "func (e *ExpectedClusterSetup) WithAction(action interface{}) *ExpectedClusterSetup {\n\te.arg0 = action\n\treturn e\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 (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 NewAction(cmd Command) Action {\n\tswitch cmd.name {\n\tcase buildCommand:\n\t\treturn NewBuildAction(afero.NewOsFs(), cmd.helmRepoName, cmd.artifactsPath)\n\tdefault:\n\t\treturn ShowAction{}\n\t}\n}", "func NewRegisterAction(dispatch Dispatch, executor cf.Executor) *HTTPRegisterAction {\n\treturn &HTTPRegisterAction{dispatch, executor}\n}", "func NewWorkloadAgent() *cobra.Command {\n\to := spoke.NewWorkloadAgentOptions()\n\tcmd := controllercmd.\n\t\tNewControllerCommandConfig(\"work-agent\", version.Get(), o.RunWorkloadAgent).\n\t\tNewCommand()\n\tcmd.Use = \"agent\"\n\tcmd.Short = \"Start the Cluster Registration Agent\"\n\n\to.AddFlags(cmd)\n\treturn cmd\n}", "func (m *GraphBaseServiceClient) AgreementAcceptances()(*i3e9b5129e2bb8b32b0374f7afe2536be6674d73df6c41d7c529f5a5432c4e0aa.AgreementAcceptancesRequestBuilder) {\n return i3e9b5129e2bb8b32b0374f7afe2536be6674d73df6c41d7c529f5a5432c4e0aa.NewAgreementAcceptancesRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) AgreementAcceptances()(*i3e9b5129e2bb8b32b0374f7afe2536be6674d73df6c41d7c529f5a5432c4e0aa.AgreementAcceptancesRequestBuilder) {\n return i3e9b5129e2bb8b32b0374f7afe2536be6674d73df6c41d7c529f5a5432c4e0aa.NewAgreementAcceptancesRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func newBreachArbiter(wallet *lnwallet.LightningWallet, db *channeldb.DB,\n\tnotifier chainntnfs.ChainNotifier, h *htlcswitch.Switch,\n\tchain lnwallet.BlockChainIO, fe lnwallet.FeeEstimator) *breachArbiter {\n\n\treturn &breachArbiter{\n\t\twallet: wallet,\n\t\tdb: db,\n\t\tnotifier: notifier,\n\t\tchainIO: chain,\n\t\thtlcSwitch: h,\n\t\testimator: fe,\n\n\t\tbreachObservers: make(map[wire.OutPoint]chan struct{}),\n\t\tbreachedContracts: make(chan *retributionInfo),\n\t\tnewContracts: make(chan *lnwallet.LightningChannel),\n\t\tsettledContracts: make(chan *wire.OutPoint),\n\t\tquit: make(chan struct{}),\n\t}\n}", "func (secretsManager *SecretsManagerV2) CreateSecretAction(createSecretActionOptions *CreateSecretActionOptions) (result SecretActionIntf, response *core.DetailedResponse, err error) {\n\treturn secretsManager.CreateSecretActionWithContext(context.Background(), createSecretActionOptions)\n}", "func NewCheckmate(winner Colour) Outcome { return Outcome{Winner: winner, Reason: checkmate} }", "func (c *Client) CreateCustomActionType(ctx context.Context, params *CreateCustomActionTypeInput, optFns ...func(*Options)) (*CreateCustomActionTypeOutput, error) {\n\tif params == nil {\n\t\tparams = &CreateCustomActionTypeInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"CreateCustomActionType\", params, optFns, addOperationCreateCustomActionTypeMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*CreateCustomActionTypeOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func NewGetConsentActionForbidden() *GetConsentActionForbidden {\n\treturn &GetConsentActionForbidden{}\n}", "func NewRecvAction(args any) *Action {\n\treturn &Action{Args: args}\n}", "func NewAliasAddAction(alias string) *AliasAddAction {\n\treturn &AliasAddAction{\n\t\talias: alias,\n\t}\n}", "func New() *Action {\n\treturn &Action{}\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 (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 NewActionAgent(\n\ttabletAlias topo.TabletAlias,\n\tdbcfgs *dbconfigs.DBConfigs,\n\tmycnf *mysqlctl.Mycnf,\n\tport, securePort int,\n\toverridesFile string,\n) (agent *ActionAgent, err error) {\n\tschemaOverrides := loadSchemaOverrides(overridesFile)\n\n\ttopoServer := topo.GetServer()\n\tmysqld := mysqlctl.NewMysqld(\"Dba\", mycnf, &dbcfgs.Dba, &dbcfgs.Repl)\n\n\tagent = &ActionAgent{\n\t\tTopoServer: topoServer,\n\t\tTabletAlias: tabletAlias,\n\t\tMysqld: mysqld,\n\t\tDBConfigs: dbcfgs,\n\t\tSchemaOverrides: schemaOverrides,\n\t\tdone: make(chan struct{}),\n\t\tHistory: history.New(historyLength),\n\t\tchangeItems: make(chan tabletChangeItem, 100),\n\t}\n\n\t// Start the binlog player services, not playing at start.\n\tagent.BinlogPlayerMap = NewBinlogPlayerMap(topoServer, &dbcfgs.App.ConnectionParams, mysqld)\n\tRegisterBinlogPlayerMap(agent.BinlogPlayerMap)\n\n\t// try to figure out the mysql port\n\tmysqlPort := mycnf.MysqlPort\n\tif mysqlPort == 0 {\n\t\t// we don't know the port, try to get it from mysqld\n\t\tvar err error\n\t\tmysqlPort, err = mysqld.GetMysqlPort()\n\t\tif err != nil {\n\t\t\tlog.Warningf(\"Cannot get current mysql port, will use 0 for now: %v\", err)\n\t\t}\n\t}\n\n\tif err := agent.Start(mysqlPort, port, securePort); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// register the RPC services from the agent\n\tagent.registerQueryService()\n\n\t// start health check if needed\n\tagent.initHeathCheck()\n\n\treturn agent, nil\n}", "func (a *ManagementApiService) CreateAdditionalCost(ctx _context.Context) apiCreateAdditionalCostRequest {\n\treturn apiCreateAdditionalCostRequest{\n\t\tapiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (policy *ticketPolicy) OnCreateNewAccount(acc *types.Account) {\n}", "func NewAction(fn ActionFn) *Action {\n\treturn &Action{\n\t\tfn: fn,\n\t\tdoneCh: make(chan struct{}),\n\t}\n}", "func NewCreateAction(viper *viper.Viper, dataMgrCli pbdatamanager.DataManagerClient,\n\treq *pb.CreateAppReq, resp *pb.CreateAppResp) *CreateAction {\n\taction := &CreateAction{viper: viper, dataMgrCli: dataMgrCli, req: req, resp: resp}\n\n\taction.resp.Seq = req.Seq\n\taction.resp.ErrCode = pbcommon.ErrCode_E_OK\n\taction.resp.ErrMsg = \"OK\"\n\n\treturn action\n}", "func NewWatcherAction() *WatcherAction {\n\tr := &WatcherAction{}\n\n\treturn r\n}", "func (_Bep20 *Bep20Transactor) IncreaseAllowance(opts *bind.TransactOpts, spender common.Address, addedValue *big.Int) (*types.Transaction, error) {\n\treturn _Bep20.contract.Transact(opts, \"increaseAllowance\", spender, addedValue)\n}", "func DeployAccessControl(auth *bind.TransactOpts, backend bind.ContractBackend, newCooAddress common.Address, newCfoAddress common.Address) (common.Address, *types.Transaction, *AccessControl, error) {\n\tparsed, err := abi.JSON(strings.NewReader(AccessControlABI))\n\tif err != nil {\n\t\treturn common.Address{}, nil, nil, err\n\t}\n\n\taddress, tx, contract, err := bind.DeployContract(auth, parsed, common.FromHex(AccessControlBin), backend, newCooAddress, newCfoAddress)\n\tif err != nil {\n\t\treturn common.Address{}, nil, nil, err\n\t}\n\treturn address, tx, &AccessControl{AccessControlCaller: AccessControlCaller{contract: contract}, AccessControlTransactor: AccessControlTransactor{contract: contract}, AccessControlFilterer: AccessControlFilterer{contract: contract}}, nil\n}", "func (_ERC20Mintable *ERC20MintableTransactor) IncreaseAllowance(opts *bind.TransactOpts, spender common.Address, addedValue *big.Int) (*types.Transaction, error) {\n\treturn _ERC20Mintable.contract.Transact(opts, \"increaseAllowance\", spender, addedValue)\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 NewActionDrop(from ID, y, x, z int, target ID, cost time.Duration) *ActionDrop {\n\treturn &ActionDrop{\n\t\t// FIXME: Figure out the actual base costs of grabbing. Probably based on the weight + size of the item vs. the character's own strength.\n\t\tAction: Action{\n\t\t\tchannel: cost / 4,\n\t\t\trecovery: cost - cost/4,\n\t\t},\n\t\tFromContainer: from,\n\t\tY: y,\n\t\tX: x,\n\t\tZ: z,\n\t\tTarget: target,\n\t}\n}", "func (_PoC *PoCTransactor) GrantAccess(opts *bind.TransactOpts, _to common.Address) (*types.Transaction, error) {\n\treturn _PoC.contract.Transact(opts, \"grantAccess\", _to)\n}", "func CreateAction(req *http.Request) (interface{}, error) {\n\tparam, err := newCreateParam4Create(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn createActionProcess(req, param)\n}" ]
[ "0.64638203", "0.61863166", "0.5534939", "0.529289", "0.5087931", "0.50345194", "0.47454304", "0.46657106", "0.4555626", "0.4545793", "0.45320782", "0.44856998", "0.4456182", "0.4451843", "0.43959028", "0.43657944", "0.43611333", "0.4357266", "0.43521774", "0.43518445", "0.4342636", "0.4329987", "0.43060848", "0.42648292", "0.42588392", "0.4252665", "0.42193332", "0.41813338", "0.41631073", "0.41591522", "0.414936", "0.4148485", "0.4148031", "0.4148031", "0.41458014", "0.41381583", "0.41272053", "0.41251236", "0.4120189", "0.4117049", "0.41026032", "0.409719", "0.409719", "0.4089132", "0.40850285", "0.4067299", "0.40628877", "0.40519452", "0.4044426", "0.40214482", "0.40111047", "0.39920577", "0.39909425", "0.3972872", "0.397195", "0.39714217", "0.39708492", "0.39696768", "0.39696768", "0.3968721", "0.39663094", "0.3965848", "0.3961613", "0.39577794", "0.39468104", "0.3944364", "0.39432076", "0.3938256", "0.3932838", "0.39273572", "0.39171672", "0.39135587", "0.38784057", "0.38568297", "0.38341925", "0.38304314", "0.38304314", "0.38224214", "0.38212886", "0.38017103", "0.37991813", "0.37962076", "0.37957823", "0.37827736", "0.37799823", "0.37791502", "0.37763605", "0.37529483", "0.37504405", "0.3749062", "0.37438357", "0.37399977", "0.37374473", "0.3736979", "0.37366566", "0.37342247", "0.37339973", "0.37281507", "0.37269688", "0.3720736" ]
0.7976986
0
AddToAccount implements the exported.AddGrantAction interface. It checks that rawAccount is a ClawbackVestingAccount with the same funder and adds the described Grant to it.
AddToAccount реализует интерфейс exported.AddGrantAction. Он проверяет, является ли rawAccount ClawbackVestingAccount с тем же funder и добавляет описанный Grant в него.
func (cga clawbackGrantAction) AddToAccount(ctx sdk.Context, rawAccount exported.VestingAccount) error { cva, ok := rawAccount.(*ClawbackVestingAccount) if !ok { return sdkerrors.Wrapf(sdkerrors.ErrNotSupported, "account %s must be a ClawbackVestingAccount, got %T", rawAccount.GetAddress(), rawAccount) } if cga.funderAddress != cva.FunderAddress { return sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, "account %s can only accept grants from account %s", rawAccount.GetAddress(), cva.FunderAddress) } cva.addGrant(ctx, cga.sk, cga.grantStartTime, cga.grantLockupPeriods, cga.grantVestingPeriods, cga.grantCoins) return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "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 (_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 (pva *PeriodicVestingAccount) AddGrant(ctx sdk.Context, action exported.AddGrantAction) error {\n\treturn action.AddToAccount(ctx, pva)\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 (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 (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 (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 (_TxRelay *TxRelayTransactor) AddToWhitelist(opts *bind.TransactOpts, addr common.Address) (*types.Transaction, error) {\n\treturn _TxRelay.contract.Transact(opts, \"addToWhitelist\", addr)\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 (ca clawbackAction) TakeFromAccount(ctx sdk.Context, rawAccount exported.VestingAccount) error {\n\tcva, ok := rawAccount.(*ClawbackVestingAccount)\n\tif !ok {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrNotSupported, \"clawback expects *ClawbackVestingAccount, got %T\", rawAccount)\n\t}\n\tif ca.requestor.String() != cva.FunderAddress {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, \"clawback can only be requested by original funder %s\", cva.FunderAddress)\n\t}\n\treturn cva.clawback(ctx, ca.dest, ca.ak, ca.bk, ca.sk)\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 (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 (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 (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 (_PermInterface *PermInterfaceTransactor) AddAdminAccount(opts *bind.TransactOpts, _acct common.Address) (*types.Transaction, error) {\n\treturn _PermInterface.contract.Transact(opts, \"addAdminAccount\", _acct)\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 (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 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 (policy *ticketPolicy) OnCreateNewAccount(acc *types.Account) {\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 (_TxRelay *TxRelayTransactorSession) AddToWhitelist(addr common.Address) (*types.Transaction, error) {\n\treturn _TxRelay.Contract.AddToWhitelist(&_TxRelay.TransactOpts, addr)\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 (_TxRelay *TxRelaySession) AddToWhitelist(addr common.Address) (*types.Transaction, error) {\n\treturn _TxRelay.Contract.AddToWhitelist(&_TxRelay.TransactOpts, addr)\n}", "func (_PermInterface *PermInterfaceTransactorSession) AddAdminAccount(_acct common.Address) (*types.Transaction, error) {\n\treturn _PermInterface.Contract.AddAdminAccount(&_PermInterface.TransactOpts, _acct)\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 (am *AccountManager) AddAccount(a *Account) {\n\tam.cmdChan <- &addAccountCmd{\n\t\ta: a,\n\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 (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 (r *RBAC) AddToWhiteList(system, uid string, permissions ...string) error {\n\tr.Cache.RemoveUser(system, uid)\n\treturn r.User.AddToWhiteList(system, uid, permissions...)\n}", "func (mam *MockAccountModel) AddAccount(email, password string) error {\n\targs := mam.Called(email, password)\n\n\treturn args.Error(0)\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 (_ChpRegistry *ChpRegistryTransactor) AddPauser(opts *bind.TransactOpts, account common.Address) (*types.Transaction, error) {\n\treturn _ChpRegistry.contract.Transact(opts, \"addPauser\", 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 (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(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 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 (_OwnedUpgradeableTokenStorage *OwnedUpgradeableTokenStorageTransactor) AddOwner(opts *bind.TransactOpts, _newOwner common.Address) (*types.Transaction, error) {\n\treturn _OwnedUpgradeableTokenStorage.contract.Transact(opts, \"addOwner\", _newOwner)\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 (cl *CustodianLedger) AddAccountToLedger(account *Bankaccount) {\n\tnewData := account\n\tcl.Ledger = append(cl.Ledger, newData)\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 (b *OGame) AddAccount(number int, lang string) (*AddAccountRes, error) {\n\treturn b.addAccount(number, lang)\n}", "func (_TTFT20 *TTFT20Transactor) RegisterWithdrawalAddress(opts *bind.TransactOpts, addr common.Address) (*types.Transaction, error) {\n\treturn _TTFT20.contract.Transact(opts, \"registerWithdrawalAddress\", addr)\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 (_Token *TokenTransactor) AddWhitelisted(opts *bind.TransactOpts, account common.Address) (*types.Transaction, error) {\n\treturn _Token.contract.Transact(opts, \"addWhitelisted\", account)\n}", "func (_PermInterface *PermInterfaceSession) AddAdminAccount(_acct common.Address) (*types.Transaction, error) {\n\treturn _PermInterface.Contract.AddAdminAccount(&_PermInterface.TransactOpts, _acct)\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 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 (_BREMFactory *BREMFactoryTransactor) AddAuditor(opts *bind.TransactOpts, _newAuditor common.Address) (*types.Transaction, error) {\n\treturn _BREMFactory.contract.Transact(opts, \"addAuditor\", _newAuditor)\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 (_TTFT20 *TTFT20Transactor) AddOwner(opts *bind.TransactOpts, _newOwner common.Address) (*types.Transaction, error) {\n\treturn _TTFT20.contract.Transact(opts, \"addOwner\", _newOwner)\n}", "func (_Pausable *PausableTransactor) AddPauser(opts *bind.TransactOpts, account common.Address) (*types.Transaction, error) {\n\treturn _Pausable.contract.Transact(opts, \"addPauser\", account)\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 (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 (_Upgradeable *UpgradeableTransactor) AddOwner(opts *bind.TransactOpts, _newOwner common.Address) (*types.Transaction, error) {\n\treturn _Upgradeable.contract.Transact(opts, \"addOwner\", _newOwner)\n}", "func (_ERC20Pausable *ERC20PausableTransactor) AddPauser(opts *bind.TransactOpts, account common.Address) (*types.Transaction, error) {\n\treturn _ERC20Pausable.contract.Transact(opts, \"addPauser\", account)\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 (_Owned *OwnedTransactor) AddOwner(opts *bind.TransactOpts, _newOwner common.Address) (*types.Transaction, error) {\n\treturn _Owned.contract.Transact(opts, \"addOwner\", _newOwner)\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 (e *EscrowAccount) AddStakeClaim(tm map[ThresholdKind]quantity.Quantity, claim StakeClaim, thresholds []ThresholdKind) error {\n\t// Compute total amount of claims excluding the claim that we are just adding. This is needed\n\t// in case the claim is being updated to avoid counting it twice.\n\ttotalClaims, err := e.StakeAccumulator.TotalClaims(tm, &claim)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, kind := range thresholds {\n\t\tq := tm[kind]\n\t\tif err := totalClaims.Add(&q); err != nil {\n\t\t\treturn fmt.Errorf(\"staking: failed to accumulate threshold: %w\", err)\n\t\t}\n\t}\n\n\t// Make sure there is sufficient stake to satisfy the claim.\n\tif e.Active.Balance.Cmp(totalClaims) < 0 {\n\t\treturn ErrInsufficientStake\n\t}\n\n\te.StakeAccumulator.AddClaimUnchecked(claim, thresholds)\n\treturn nil\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 (_Userable *UserableTransactor) AddAuditor(opts *bind.TransactOpts, _newAuditor common.Address) (*types.Transaction, error) {\n\treturn _Userable.contract.Transact(opts, \"addAuditor\", _newAuditor)\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 (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 (a *StoragePowerActorCode_I) AddBalance(rt Runtime, minerAddr addr.Address) {\n\tRT_MinerEntry_ValidateCaller_DetermineFundsLocation(rt, minerAddr, vmr.MinerEntrySpec_MinerOnly)\n\n\tmsgValue := rt.ValueReceived()\n\n\th, st := a.State(rt)\n\tnewTable, ok := autil.BalanceTable_WithAdd(st.EscrowTable(), minerAddr, msgValue)\n\tif !ok {\n\t\trt.AbortStateMsg(\"Escrow operation failed\")\n\t}\n\tst.Impl().EscrowTable_ = newTable\n\tUpdateRelease(rt, h, st)\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 (s *Service) AccountCreate(c *gin.Context, roleID model.AccessRole) error {\n\treturn s.IsLowerRole(c, roleID)\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 AccountGrant() GrantBuilder {\n\treturn &CurrentGrantBuilder{\n\t\tgrantType: accountType,\n\t}\n}", "func (a SubAccountClient) PostSubAccountTransfer(req *rest3.RequestForSubAccountTransfer) (rest3.ResponseForSubAccountTransfer, error) {\n\tpanic(\"implement me\")\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 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 (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 (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 (bal *bucketAccessListener) Add(ctx context.Context, obj *v1alpha1.BucketAccess) error {\n\tklog.V(1).Infof(\"bucketAccessListener: add called for bucket access %s\", obj.Name)\n\n\t// Verify this bucket access is for this provisioner\n\tif !strings.EqualFold(obj.Spec.Provisioner, bal.provisionerName) {\n\t\treturn nil\n\t}\n\n\tbucketInstanceName := obj.Spec.BucketInstanceName\n\tbucket, err := bal.bucketAccessClient.ObjectstorageV1alpha1().Buckets().Get(ctx, bucketInstanceName, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to get bucket instance %s: %+v\", bucketInstanceName, err)\n\t}\n\n\treq := osspec.ProvisionerGrantBucketAccessRequest{\n\t\tPrincipal: obj.Spec.Principal,\n\t\tAccessPolicy: obj.Spec.PolicyActionsConfigMapData,\n\t\tBucketContext: map[string]string{},\n\t}\n\n\tswitch bucket.Spec.Protocol.Name {\n\tcase v1alpha1.ProtocolNameS3:\n\t\treq.BucketName = bucket.Spec.Protocol.S3.BucketName\n\t\treq.Region = bucket.Spec.Protocol.S3.Region\n\t\treq.BucketContext[\"Version\"] = bucket.Spec.Protocol.S3.Version\n\t\treq.BucketContext[\"SignatureVersion\"] = string(bucket.Spec.Protocol.S3.SignatureVersion)\n\t\treq.BucketContext[\"Endpoint\"] = bucket.Spec.Protocol.S3.Endpoint\n\tcase v1alpha1.ProtocolNameAzure:\n\t\treq.BucketName = bucket.Spec.Protocol.AzureBlob.ContainerName\n\t\treq.BucketContext[\"StorageAccount\"] = bucket.Spec.Protocol.AzureBlob.StorageAccount\n\tcase v1alpha1.ProtocolNameGCS:\n\t\treq.BucketName = bucket.Spec.Protocol.GCS.BucketName\n\t\treq.BucketContext[\"ServiceAccount\"] = bucket.Spec.Protocol.GCS.ServiceAccount\n\t\treq.BucketContext[\"PrivateKeyName\"] = bucket.Spec.Protocol.GCS.PrivateKeyName\n\t\treq.BucketContext[\"ProjectID\"] = bucket.Spec.Protocol.GCS.ProjectID\n\tdefault:\n\t\treturn fmt.Errorf(\"unknown protocol: %s\", bucket.Spec.Protocol.Name)\n\t}\n\n\t// TODO set grpc timeout\n\trsp, err := bal.provisionerClient.ProvisionerGrantBucketAccess(ctx, &req)\n\tif err != nil {\n\t\tklog.Errorf(\"error calling ProvisionerGrantBucketAccess: %v\", err)\n\t\treturn err\n\t}\n\tklog.V(1).Infof(\"provisioner returned grant bucket access response %v\", rsp)\n\n\t// Only update the principal in the BucketAccess if it wasn't set because\n\t// that means that the provisioner created one\n\tif len(obj.Spec.Principal) == 0 {\n\t\terr = bal.updatePrincipal(ctx, obj.Name, *rsp)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Only create the secret with credentials if serviveAccount isn't set.\n\t// If serviceAccount is set then authorization happens out of band in the\n\t// cloud provider\n\tif len(obj.Spec.ServiceAccount) == 0 {\n\t\tsecret := v1.Secret{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: generateSecretName(obj.UID),\n\t\t\t},\n\t\t\tStringData: map[string]string{\n\t\t\t\t\"CredentialsFilePath\": rsp.CredentialsFilePath,\n\t\t\t\t\"CredentialsFileContents\": rsp.CredentialsFileContents,\n\t\t\t},\n\t\t\tType: v1.SecretTypeOpaque,\n\t\t}\n\t\t// It's unlikely but should probably handle retries on rare case of collision\n\t\t_, err = bal.kubeClient.CoreV1().Secrets(\"objectstorage-system\").Create(ctx, &secret, metav1.CreateOptions{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// update bucket access status to granted\n\treturn bal.updateStatus(ctx, obj.Name, \"Permissions Granted\", true)\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 (client *Client) GrantInstanceToVbr(request *GrantInstanceToVbrRequest) (response *GrantInstanceToVbrResponse, err error) {\n\tresponse = CreateGrantInstanceToVbrResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func (s *StateDB) CreateAccount(addr types.AddressHash) {\n\tnew, prev := s.createObject(addr)\n\tif prev != nil {\n\t\tnew.setBalance(prev.data.Balance)\n\t}\n}", "func AddAccount(name string) (ethcmn.Address, error) {\n\tdir := getDir(accountDir)\n\tdb, err := leveldb.OpenFile(dir, nil)\n\tif err != nil {\n\t\treturn ethcmn.Address{}, err\n\t}\n\tdefer db.Close()\n\n\tkey := []byte(name)\n\tif _, err = db.Get(key, nil); err == nil {\n\t\treturn ethcmn.Address{}, errors.New(\"you are trying to override an existing private key name. Please delete it first\")\n\t}\n\n\tbuf := cosmoscli.BufferStdin()\n\tpassword, err := cosmoscli.GetCheckPassword(NewPassphrasePrompt, NewPassphrasePromptRepeat, buf)\n\tif err != nil {\n\t\treturn ethcmn.Address{}, err\n\t}\n\n\tacc, err := ks.NewAccount(password)\n\tif err != nil {\n\t\treturn ethcmn.Address{}, err\n\t}\n\n\tif err = db.Put(key, acc.Address.Bytes(), nil); err != nil {\n\t\treturn ethcmn.Address{}, err\n\t}\n\n\treturn acc.Address, nil\n}", "func (ec *executionContext) field_Mutation_createAccount_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) {\n\tvar err error\n\targs := map[string]interface{}{}\n\tvar arg0 model.NewAccount\n\tif tmp, ok := rawArgs[\"input\"]; ok {\n\t\tctx := graphql.WithPathContext(ctx, graphql.NewPathWithField(\"input\"))\n\t\targ0, err = ec.unmarshalNNewAccount2githubᚗcomᚋannoyingᚑorangeᚋecpᚑapiᚋgraphᚋmodelᚐNewAccount(ctx, tmp)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\targs[\"input\"] = arg0\n\treturn args, nil\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 (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 (r Runner) AddGenesisAccount(ctx context.Context, address, coins string) error {\n\treturn r.run(ctx, runOptions{}, r.cc.AddGenesisAccountCommand(address, coins))\n}", "func (c *TransferRouter) postAccountTransaction(userID id.User, origDep *model.Depository, recDep *model.Depository, amount model.Amount, transferType model.TransferType, requestID string) (*accounts.Transaction, error) {\n\tif c.accountsClient == nil {\n\t\treturn nil, errors.New(\"accounts enabled but nil client\")\n\t}\n\n\t// Let's lookup both accounts. Either account can be \"external\" (meaning of a RoutingNumber Accounts doesn't control).\n\t// When the routing numbers don't match we can't do much verify the remote account as we likely don't have Account-level access.\n\t//\n\t// TODO(adam): What about an FI that handles multiple routing numbers? Should Accounts expose which routing numbers it currently supports?\n\treceiverAccount, err := c.accountsClient.SearchAccounts(requestID, userID, recDep)\n\tif err != nil || receiverAccount == nil {\n\t\treturn nil, fmt.Errorf(\"error reading account user=%s receiver depository=%s: %v\", userID, recDep.ID, err)\n\t}\n\torigAccount, err := c.accountsClient.SearchAccounts(requestID, userID, origDep)\n\tif err != nil || origAccount == nil {\n\t\treturn nil, fmt.Errorf(\"error reading account user=%s originator depository=%s: %v\", userID, origDep.ID, err)\n\t}\n\t// Submit the transactions to Accounts (only after can we go ahead and save off the Transfer)\n\ttransaction, err := c.accountsClient.PostTransaction(requestID, userID, createTransactionLines(origAccount, receiverAccount, amount, transferType))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating transaction for transfer user=%s: %v\", userID, err)\n\t}\n\tc.logger.Log(\"transfers\", fmt.Sprintf(\"created transaction=%s for user=%s amount=%s\", transaction.ID, userID, amount.String()))\n\treturn transaction, 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 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 (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 AddAccount(username string, email string, password string, phone string, showname string, birthday string) error {\r\n\tsqlprepare, err := ConnectDB().Prepare(\"INSERT INTO account(username,email,`password`,`phone`,showname,birthday) VALUES(?,?,?,?,?,?)\")\r\n\tdefer ConnectDB().Close()\r\n\tif err != nil {\r\n\t\tpanic(err.Error())\r\n\t}\r\n\t_, err = sqlprepare.Exec(username, email, password, phone, showname, birthday)\r\n\treturn err\r\n}", "func (_ElvToken *ElvTokenTransactor) AddPauser(opts *bind.TransactOpts, account common.Address) (*types.Transaction, error) {\n\treturn _ElvToken.contract.Transact(opts, \"addPauser\", account)\n}", "func (_SimpleSavingsWallet *SimpleSavingsWalletTransactor) ClaimHeirOwnership(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _SimpleSavingsWallet.contract.Transact(opts, \"claimHeirOwnership\")\n}", "func (_TTFT20 *TTFT20TransactorSession) RegisterWithdrawalAddress(addr common.Address) (*types.Transaction, error) {\n\treturn _TTFT20.Contract.RegisterWithdrawalAddress(&_TTFT20.TransactOpts, addr)\n}", "func (smartContract) invoke_AddClaim(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\r\n\tmessage := fmt.Sprintf(\"invokeAddClaim called with args: %s\\n\", args)\r\n\tlog.Debugf(message)\r\n\r\n\t// Check arguments\r\n\tif len(args) < 3 {\r\n\t\tlog.Errorf(message)\r\n\t\treturn nil, errors.New(message)\r\n\t}\r\n\tfrom, err := strconv.Atoi(args[0])\r\n\tif err != nil {\r\n\t\tlog.Errorf(\"strconv.Atoi(args[0]) error: %s\", err.Error())\r\n\t\treturn nil, err\r\n\t}\r\n\tto, err := strconv.Atoi(args[1])\r\n\tif err != nil {\r\n\t\tlog.Errorf(\"strconv.Atoi(args[1]) error: %s\", err.Error())\r\n\t\treturn nil, err\r\n\t}\r\n\tvalue, err := strconv.ParseFloat(args[2], 64)\r\n\tif err != nil {\r\n\t\tlog.Errorf(\"strconv.ParseFloat(args[2], 64) error: %s\", err.Error())\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\t// We are not interested in \"negative claims\"\r\n\tif value < 0.0 {\r\n\t\treturn nil, nil\r\n\t}\r\n\r\n\t// Load existing data\r\n\tnettingTable, err := load(stub)\r\n\tcheckCriticalError(err)\r\n\r\n\tnettingTable.AddClaim(from, to, value)\r\n\r\n\t// Save new data\r\n\terr = save(nettingTable, stub)\r\n\tcheckCriticalError(err)\r\n\r\n\treturn nil, nil\r\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 (_ChpRegistry *ChpRegistryTransactorSession) AddPauser(account common.Address) (*types.Transaction, error) {\n\treturn _ChpRegistry.Contract.AddPauser(&_ChpRegistry.TransactOpts, account)\n}", "func (n *noopRules) Grant(rule *Rule) error {\n\treturn nil\n}", "func Claim(cfg *setting.Setting, param *ClaimParam, debug bool) error {\n\tmutex.Lock()\n\tdest, err := wallet.NewAddress(&cfg.DBConfig, pwd, true)\n\tif err != nil {\n\t\tmutex.Unlock()\n\t\treturn err\n\t}\n\tmutex.Unlock()\n\tadrstr := strings.ToUpper(hex.EncodeToString(dest.Address(cfg.Config)))\n\tenc := make([]rune, len(adrstr)+1)\n\tfor i, c := range adrstr {\n\t\tif c >= '0' && c <= '8' {\n\t\t\tc = c - '0' + 'G'\n\t\t}\n\t\tenc[i] = c\n\t}\n\tenc[len(adrstr)] = 'Z'\n\tapis := getOldAPIs(oldServers)\n\ttr := gadk.Transfer{\n\t\tAddress: pobAddress,\n\t\tValue: param.Amount,\n\t\tMessage: gadk.Trytes(enc),\n\t}\n\t_, f := gadk.GetBestPoW()\n\tif debug {\n\t\tf = nil\n\t}\n\tfor _, api := range apis {\n\t\t_, err = gadk.Send(api, param.Seed, 2, []gadk.Transfer{tr}, f)\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn err\n}", "func (db *boltDB) createAccount(pa providerAccount) error {\n\treturn db.Update(func(tx *bolt.Tx) error {\n\t\tbucket, err := tx.CreateBucketIfNotExists(pa.key())\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"create bucket %s: %v\", pa.key(), err)\n\t\t}\n\t\tfor _, b := range bucketNames {\n\t\t\t_, err := bucket.CreateBucketIfNotExists([]byte(b))\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"create account bucket %s: %v\", b, err)\n\t\t\t}\n\t\t}\n\t\treturn nil\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 (r *RBAC) AddToBlackList(system, uid string, permissions ...string) error {\n\tr.Cache.RemoveUser(system, uid)\n\treturn r.User.AddToBlackList(system, uid, permissions...)\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}" ]
[ "0.70387936", "0.6084376", "0.58506024", "0.5656218", "0.5626727", "0.5414569", "0.5300817", "0.51898015", "0.511495", "0.50976485", "0.5083623", "0.5055534", "0.49965897", "0.48901007", "0.48723358", "0.48572427", "0.48206356", "0.4800977", "0.4778801", "0.47696823", "0.47692096", "0.47624657", "0.47552904", "0.4735677", "0.4697048", "0.4689067", "0.46874264", "0.46766818", "0.46751824", "0.46681306", "0.4662258", "0.46585393", "0.46585217", "0.46509168", "0.46393386", "0.4626084", "0.46128264", "0.45912176", "0.4524454", "0.45233998", "0.4514737", "0.45099247", "0.4499597", "0.449856", "0.44962323", "0.44956273", "0.44858536", "0.44815806", "0.44797269", "0.44795346", "0.44583756", "0.44481325", "0.4445018", "0.44355434", "0.44228953", "0.44228613", "0.44120368", "0.4410376", "0.4409666", "0.44011837", "0.4390004", "0.43855053", "0.43809003", "0.43780956", "0.43677598", "0.43529293", "0.43515024", "0.43426096", "0.43418363", "0.43366686", "0.4328826", "0.4328809", "0.43241587", "0.4320327", "0.43151334", "0.43144467", "0.43131888", "0.43097508", "0.4307694", "0.43003067", "0.43000188", "0.42974287", "0.42959964", "0.42932743", "0.42913035", "0.42820525", "0.4278522", "0.42763773", "0.42620042", "0.4259967", "0.4259799", "0.42589027", "0.4258176", "0.42568356", "0.42560223", "0.4255191", "0.42520204", "0.42490008", "0.42459285", "0.42436308" ]
0.7568594
0
addGrant merges a new clawback vesting grant into an existing ClawbackVestingAccount.
addGrant объединяет новый премиальный ветинговый грант с существующим ClawbackVestingAccount.
func (va *ClawbackVestingAccount) addGrant(ctx sdk.Context, sk StakingKeeper, grantStartTime int64, grantLockupPeriods, grantVestingPeriods []Period, grantCoins sdk.Coins) { // how much is really delegated? bondedAmt := sk.GetDelegatorBonded(ctx, va.GetAddress()) unbondingAmt := sk.GetDelegatorUnbonding(ctx, va.GetAddress()) delegatedAmt := bondedAmt.Add(unbondingAmt) delegated := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), delegatedAmt)) // discover what has been slashed oldDelegated := va.DelegatedVesting.Add(va.DelegatedFree...) slashed := oldDelegated.Sub(coinsMin(oldDelegated, delegated)) // rebase the DV + DF by capping slashed at the current unvested amount unvested := va.OriginalVesting.Sub(va.GetVestedOnly(ctx.BlockTime())) newSlashed := coinsMin(slashed, unvested) newDelegated := delegated.Add(newSlashed...) // modify schedules for the new grant newLockupStart, newLockupEnd, newLockupPeriods := DisjunctPeriods(va.StartTime, grantStartTime, va.LockupPeriods, grantLockupPeriods) newVestingStart, newVestingEnd, newVestingPeriods := DisjunctPeriods(va.StartTime, grantStartTime, va.GetVestingPeriods(), grantVestingPeriods) if newLockupStart != newVestingStart { panic("bad start time calculation") } va.StartTime = newLockupStart va.EndTime = max64(newLockupEnd, newVestingEnd) va.LockupPeriods = newLockupPeriods va.VestingPeriods = newVestingPeriods va.OriginalVesting = va.OriginalVesting.Add(grantCoins...) // cap DV at the current unvested amount, DF rounds out to newDelegated unvested2 := va.GetVestingCoins(ctx.BlockTime()) va.DelegatedVesting = coinsMin(newDelegated, unvested2) va.DelegatedFree = newDelegated.Sub(va.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 (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 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) 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 (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 (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 (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 (_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 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 (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 (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 (_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 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 (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 (s *BasePlSqlParserListener) EnterGrant_statement(ctx *Grant_statementContext) {}", "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 (n *noopRules) Grant(rule *Rule) error {\n\treturn 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 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 (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 (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 (_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 (_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 (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 (_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 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 (_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 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 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 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 (e *EscrowAccount) AddStakeClaim(tm map[ThresholdKind]quantity.Quantity, claim StakeClaim, thresholds []ThresholdKind) error {\n\t// Compute total amount of claims excluding the claim that we are just adding. This is needed\n\t// in case the claim is being updated to avoid counting it twice.\n\ttotalClaims, err := e.StakeAccumulator.TotalClaims(tm, &claim)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, kind := range thresholds {\n\t\tq := tm[kind]\n\t\tif err := totalClaims.Add(&q); err != nil {\n\t\t\treturn fmt.Errorf(\"staking: failed to accumulate threshold: %w\", err)\n\t\t}\n\t}\n\n\t// Make sure there is sufficient stake to satisfy the claim.\n\tif e.Active.Balance.Cmp(totalClaims) < 0 {\n\t\treturn ErrInsufficientStake\n\t}\n\n\te.StakeAccumulator.AddClaimUnchecked(claim, thresholds)\n\treturn nil\n}", "func (obj *Facility) AppendTransact(transact *Transaction) bool {\n\tif obj.tb.Len() != 0 {\n\t\t// Facility is busy\n\t\treturn false\n\t}\n\tobj.BaseObj.AppendTransact(transact)\n\ttransact.SetHolder(obj.name)\n\tadvance := obj.GenerateAdvance()\n\tobj.sumAdvance += float64(advance)\n\ttransact.SetTiсks(advance)\n\tif transact.GetParameter(\"Facility\") != nil {\n\t\tobj.bakupFacilityName = transact.GetParameter(\"Facility\").(string)\n\t}\n\ttransact.SetParameter(\"Facility\", obj.name)\n\tobj.HoldedTransactID = transact.GetID()\n\tobj.tb.Push(transact)\n\tobj.cntTransact++\n\treturn true\n}", "func AddTenant(m *Tenant) (id int64, err error) {\n\to := orm.NewOrm()\n\tid, err = o.Insert(m)\n\treturn\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 (_BaseAccessControlGroup *BaseAccessControlGroupTransactor) GrantAccess(opts *bind.TransactOpts, candidate common.Address) (*types.Transaction, error) {\n\treturn _BaseAccessControlGroup.contract.Transact(opts, \"grantAccess\", candidate)\n}", "func Add(mgr manager.Manager) error {\n\tr := newReconciler(mgr)\n\treturn add(mgr, r, r.SecretTriggerCertMerge)\n}", "func (p *ResourceCondition) addTenantToFilter(action string, tenant tenantMatcher) {\n\tp.actionTenantFilter[action] = append(p.actionTenantFilter[action], tenant)\n}", "func (s *BasePlSqlParserListener) EnterGrant_object_name(ctx *Grant_object_nameContext) {}", "func (_WELV9 *WELV9Transactor) Withdraw(opts *bind.TransactOpts, wad *big.Int) (*types.Transaction, error) {\n\treturn _WELV9.contract.Transact(opts, \"withdraw\", wad)\n}", "func NewRedirectGrant(url string) GrantHandler {\n\treturn &redirectGrant{url}\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 (_BaseLibrary *BaseLibraryTransactor) AddReviewerGroup(opts *bind.TransactOpts, group common.Address) (*types.Transaction, error) {\n\treturn _BaseLibrary.contract.Transact(opts, \"addReviewerGroup\", group)\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 (_BREMFactory *BREMFactoryTransactor) AddAuditor(opts *bind.TransactOpts, _newAuditor common.Address) (*types.Transaction, error) {\n\treturn _BREMFactory.contract.Transact(opts, \"addAuditor\", _newAuditor)\n}", "func (_DelegateProfile *DelegateProfileTransactor) Withdraw(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _DelegateProfile.contract.Transact(opts, \"withdraw\")\n}", "func NewGrantCheck(check GrantChecker, handler GrantHandler, errorHandler GrantErrorHandler) osinserver.AuthorizeHandler {\n\treturn &GrantCheck{check, handler, errorHandler}\n}", "func AddTenantHook(hookPoint boil.HookPoint, tenantHook TenantHook) {\n\tswitch hookPoint {\n\tcase boil.AfterSelectHook:\n\t\ttenantAfterSelectHooks = append(tenantAfterSelectHooks, tenantHook)\n\tcase boil.BeforeInsertHook:\n\t\ttenantBeforeInsertHooks = append(tenantBeforeInsertHooks, tenantHook)\n\tcase boil.AfterInsertHook:\n\t\ttenantAfterInsertHooks = append(tenantAfterInsertHooks, tenantHook)\n\tcase boil.BeforeUpdateHook:\n\t\ttenantBeforeUpdateHooks = append(tenantBeforeUpdateHooks, tenantHook)\n\tcase boil.AfterUpdateHook:\n\t\ttenantAfterUpdateHooks = append(tenantAfterUpdateHooks, tenantHook)\n\tcase boil.BeforeDeleteHook:\n\t\ttenantBeforeDeleteHooks = append(tenantBeforeDeleteHooks, tenantHook)\n\tcase boil.AfterDeleteHook:\n\t\ttenantAfterDeleteHooks = append(tenantAfterDeleteHooks, tenantHook)\n\tcase boil.BeforeUpsertHook:\n\t\ttenantBeforeUpsertHooks = append(tenantBeforeUpsertHooks, tenantHook)\n\tcase boil.AfterUpsertHook:\n\t\ttenantAfterUpsertHooks = append(tenantAfterUpsertHooks, tenantHook)\n\t}\n}", "func (_TokenStakingEscrow *TokenStakingEscrowTransactor) WithdrawToManagedGrantee(opts *bind.TransactOpts, operator common.Address) (*types.Transaction, error) {\n\treturn _TokenStakingEscrow.contract.Transact(opts, \"withdrawToManagedGrantee\", operator)\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 (_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 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 (_IWETH *IWETHTransactor) Withdraw(opts *bind.TransactOpts, arg0 *big.Int) (*types.Transaction, error) {\r\n\treturn _IWETH.contract.Transact(opts, \"withdraw\", arg0)\r\n}", "func (_Wmatic *WmaticTransactor) Withdraw(opts *bind.TransactOpts, wad *big.Int) (*types.Transaction, error) {\n\treturn _Wmatic.contract.Transact(opts, \"withdraw\", wad)\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 (_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 (f *fabric) addClaim(id, x, y, w, h int) {\n\tif f.m == nil { // Harita bos ise olusturuluyor\n\t\tf.m = make(map[xy]int)\n\t}\n\n\tfor i := 0; i < w; i++ {\n\t\tfor j := 0; j < h; j++ {\n\t\t\tf.m[xy{x + i, y + j}]++ // Cizme islemi karenin degeri bir arttiliyor kesisim bulmak icin ideal\n\t\t}\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 *AWSAccountBindingApprovalReconciler) addFinalizer(ctx context.Context) (*ctrl.Result, error) {\n\tlgr := r.Log.WithValues(\"task\", \"addFinalizer\")\n\tlgr.Info(\"starting\")\n\tdefer lgr.Info(\"ending\")\n\n\t// call handler\n\tif res, err := r.handleFinalizer(ctx, controllerutil.AddFinalizer); reconc.ShouldHaltOrRequeue(res, err) {\n\t\tif err != nil {\n\t\t\tlgr.Error(err, \"error handling finalizer\")\n\t\t}\n\t\treturn res, err\n\t}\n\n\treturn reconc.ContinueReconciling()\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactor) Withdraw(opts *bind.TransactOpts, _member common.Address) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.contract.Transact(opts, \"withdraw\", _member)\n}", "func (m *LeaseMutation) AddAgetenant(i int) {\n\tif m.addagetenant != nil {\n\t\t*m.addagetenant += i\n\t} else {\n\t\tm.addagetenant = &i\n\t}\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 (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 (m *MockFormatter) AccessGrant(e entity.OauthAccessGrant) entity.OauthAccessGrantJSON {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AccessGrant\", e)\n\tret0, _ := ret[0].(entity.OauthAccessGrantJSON)\n\treturn ret0\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 (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 (this *Handler) AddCred(cred scanners.Credential) error {\n\tthis.creds = append(this.creds, cred)\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 (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 (_TokenStakingEscrow *TokenStakingEscrowSession) TokenGrant() (common.Address, error) {\n\treturn _TokenStakingEscrow.Contract.TokenGrant(&_TokenStakingEscrow.CallOpts)\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 add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(ControllerName, mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to primary resource KeycloakClient\n\terr = c.Watch(&source.Kind{Type: &kc.KeycloakClient{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Make sure to watch the credential secrets\n\terr = c.Watch(&source.Kind{Type: &corev1.Secret{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &kc.KeycloakClient{},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (p *SharePool) Withdraw(tokenDst, shareSrc, shareAmount *quantity.Quantity) error {\n\ttokens, err := p.tokensForShares(shareAmount)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = shareSrc.Sub(shareAmount); err != nil {\n\t\treturn err\n\t}\n\n\tif err = p.TotalShares.Sub(shareAmount); err != nil {\n\t\treturn err\n\t}\n\n\tif err = quantity.Move(tokenDst, &p.Balance, tokens); 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 (_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 Seal(secret config.SecretsManager, ref *reference.Ref, spec *Spec) (*Grant, error) {\n\tgrt := &Grant{Spec: spec}\n\n\tif s := spec.GetPlaintext(); s != nil {\n\t\tgrt.EncryptedReference = PlaintextGrant(ref)\n\t} else if s := spec.GetSymmetric(); s != nil {\n\t\tsecret, err := secret.Provider(s.PublicID)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tencRef, err := SymmetricGrant(ref, secret)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tgrt.EncryptedReference = encRef\n\t} else if s := spec.GetOpenPGP(); s != nil {\n\t\tencRef, err := OpenPGPGrant(ref, s.PublicKey, secret.OpenPGP)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tgrt.EncryptedReference = encRef\n\t} else {\n\t\treturn nil, fmt.Errorf(\"grant type %v not recognised\", s)\n\t}\n\n\treturn grt, nil\n}", "func (_Smartchef *SmartchefTransactor) Withdraw(opts *bind.TransactOpts, _amount *big.Int) (*types.Transaction, error) {\n\treturn _Smartchef.contract.Transact(opts, \"withdraw\", _amount)\n}", "func AddGuestTransaction(m *Guests, o orm.Ormer) (id int64, err error) {\n\tid, err = o.Insert(m)\n\treturn\n}", "func (_Lmc *LmcTransactor) Withdraw(opts *bind.TransactOpts, _tokenAmount *big.Int) (*types.Transaction, error) {\n\treturn _Lmc.contract.Transact(opts, \"withdraw\", _tokenAmount)\n}", "func (a AuthorizerFunc) GrantLogin(user string, hostID string, hostIDType string, action string) (bool, error) {\n\treturn a(user, hostID, hostIDType, action)\n}", "func (_Wmatic *WmaticTransactorSession) Withdraw(wad *big.Int) (*types.Transaction, error) {\n\treturn _Wmatic.Contract.Withdraw(&_Wmatic.TransactOpts, wad)\n}", "func (_TxRelay *TxRelayTransactor) AddToWhitelist(opts *bind.TransactOpts, addr common.Address) (*types.Transaction, error) {\n\treturn _TxRelay.contract.Transact(opts, \"addToWhitelist\", addr)\n}", "func (s *Scope) AddBaggage(key string, value string) {\n\ttracergo.AddBaggage(s.Span, key, value)\n}", "func (client *Client) GrantInstanceToVbr(request *GrantInstanceToVbrRequest) (response *GrantInstanceToVbrResponse, err error) {\n\tresponse = CreateGrantInstanceToVbrResponse()\n\terr = client.DoAction(request, response)\n\treturn\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 (s *StashList) AddStash(ctx context.Context, vw types.ValueWriter, stashAddr hash.Hash) (hash.Hash, error) {\n\tstashID := strconv.Itoa(s.lastIdx + 1)\n\n\tame := s.am.Editor()\n\terr := ame.Add(ctx, stashID, stashAddr)\n\tif err != nil {\n\t\treturn hash.Hash{}, err\n\t}\n\n\ts.am, err = ame.Flush(ctx)\n\tif err != nil {\n\t\treturn hash.Hash{}, err\n\t}\n\treturn s.updateStashListMap(ctx, vw)\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 DeployGatekeeper(auth *bind.TransactOpts, backend bind.ContractBackend, _token common.Address) (common.Address, *types.Transaction, *Gatekeeper, error) {\n\tparsed, err := abi.JSON(strings.NewReader(GatekeeperABI))\n\tif err != nil {\n\t\treturn common.Address{}, nil, nil, err\n\t}\n\taddress, tx, contract, err := bind.DeployContract(auth, parsed, common.FromHex(GatekeeperBin), backend, _token)\n\tif err != nil {\n\t\treturn common.Address{}, nil, nil, err\n\t}\n\treturn address, tx, &Gatekeeper{GatekeeperCaller: GatekeeperCaller{contract: contract}, GatekeeperTransactor: GatekeeperTransactor{contract: contract}, GatekeeperFilterer: GatekeeperFilterer{contract: contract}}, nil\n}", "func (_TokenStakingEscrow *TokenStakingEscrowCallerSession) TokenGrant() (common.Address, error) {\n\treturn _TokenStakingEscrow.Contract.TokenGrant(&_TokenStakingEscrow.CallOpts)\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 (_BaseLibrary *BaseLibraryTransactor) AddContributorGroup(opts *bind.TransactOpts, group common.Address) (*types.Transaction, error) {\n\treturn _BaseLibrary.contract.Transact(opts, \"addContributorGroup\", group)\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(\"gatlingtask-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 GatlingTask\n\terr = c.Watch(&source.Kind{Type: &tpokkiv1alpha1.GatlingTask{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to secondary resource Pods and requeue the owner GatlingTask\n\terr = c.Watch(&source.Kind{Type: &appsv1.Deployment{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &tpokkiv1alpha1.GatlingTask{},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to secondary resource ConfigMap and requeue the owner GatlingTask\n\terr = c.Watch(&source.Kind{Type: &corev1.ConfigMap{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &tpokkiv1alpha1.GatlingTask{},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (_TokenStakingEscrow *TokenStakingEscrowTransactor) Withdraw(opts *bind.TransactOpts, operator common.Address) (*types.Transaction, error) {\n\treturn _TokenStakingEscrow.contract.Transact(opts, \"withdraw\", operator)\n}", "func (c *context) WgAdd(delta int) {\n\tc.waitGroup.Add(delta)\n}", "func (_Logger *LoggerTransactor) LogStakeWithdraw(opts *bind.TransactOpts, committed common.Address, amount *big.Int, batch_id *big.Int) (*types.Transaction, error) {\n\treturn _Logger.contract.Transact(opts, \"logStakeWithdraw\", committed, amount, batch_id)\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 addStagedSigner(notaryRepo client.Repository, newSigner data.RoleName, signerKeys []data.PublicKey) {\n\t// create targets/<username>\n\tnotaryRepo.AddDelegationRoleAndKeys(newSigner, signerKeys)\n\tnotaryRepo.AddDelegationPaths(newSigner, []string{\"\"})\n\n\t// create targets/releases\n\tnotaryRepo.AddDelegationRoleAndKeys(trust.ReleasesRole, signerKeys)\n\tnotaryRepo.AddDelegationPaths(trust.ReleasesRole, []string{\"\"})\n}", "func (b *PlanBuilder) AddConnectPhase(plan *storage.OperationPlan, trustedCluster storage.TrustedCluster) error {\n\tbytes, err := storage.MarshalTrustedCluster(trustedCluster)\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\tplan.Phases = append(plan.Phases, storage.OperationPhase{\n\t\tID: phases.ConnectPhase,\n\t\tDescription: fmt.Sprintf(\"Connect to Gravity Hub %v\",\n\t\t\ttrustedCluster.GetName()),\n\t\tData: &storage.OperationPhaseData{\n\t\t\tServer: &b.Master,\n\t\t\tTrustedCluster: bytes,\n\t\t},\n\t\tRequires: []string{ossphases.RuntimePhase},\n\t\tStep: 8,\n\t})\n\treturn nil\n}" ]
[ "0.7331163", "0.7113666", "0.55019873", "0.5447035", "0.54171383", "0.539944", "0.53757775", "0.528504", "0.5252317", "0.52441466", "0.52223444", "0.5207451", "0.5137339", "0.51206416", "0.50980806", "0.5086144", "0.49832323", "0.49606624", "0.4951147", "0.49187273", "0.4871348", "0.48374197", "0.4823577", "0.47955072", "0.4794888", "0.4776616", "0.47117308", "0.4669261", "0.4666374", "0.46568024", "0.46529588", "0.46432397", "0.46197397", "0.45933405", "0.4589699", "0.4575584", "0.45622855", "0.45452762", "0.45407313", "0.44730878", "0.44706523", "0.44515884", "0.44418055", "0.4440541", "0.44367248", "0.4423879", "0.43928018", "0.43833715", "0.4382374", "0.43594477", "0.43562815", "0.43516108", "0.4351475", "0.43473408", "0.4329847", "0.4321245", "0.43165305", "0.43152043", "0.4292013", "0.42914504", "0.42889822", "0.42867324", "0.42866", "0.42828035", "0.4279926", "0.42754656", "0.42739725", "0.4269549", "0.4262396", "0.4243173", "0.42424712", "0.42352143", "0.422736", "0.42208287", "0.42205748", "0.4217174", "0.4216062", "0.4194851", "0.41897792", "0.4188728", "0.41874108", "0.4171279", "0.4166087", "0.4165034", "0.4163577", "0.41632545", "0.4158633", "0.41584706", "0.4154709", "0.4152258", "0.4149887", "0.4149555", "0.41487604", "0.41242623", "0.41209364", "0.4120907", "0.41203383", "0.41157416", "0.41112125", "0.41105625" ]
0.73836535
0
GetFunder implements the exported.ClawbackVestingAccountI interface.
GetFunder реализует интерфейс exported.ClawbackVestingAccountI.
func (va ClawbackVestingAccount) GetFunder() sdk.AccAddress { addr, err := sdk.AccAddressFromBech32(va.FunderAddress) if err != nil { panic(err) } return addr }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (svc *Service) GetFundsForProposalByFunder(req client.GetFundsForProposalByFunderRequest, reply *client.GetFundsForProposalByFunderReply) error {\n\t// Validate parameters\n\terr := req.Funder.Err()\n\tif err != nil {\n\t\treturn errors.New(\"invalid funder address\")\n\t}\n\n\tamount := svc.proposalMaster.ProposalFund.GetFundsForProposalByFunder(req.ProposalId, req.Funder)\n\t*reply = client.GetFundsForProposalByFunderReply{\n\t\tAmount: *amount,\n\t}\n\n\treturn nil\n}", "func GetFactionLedger(hc *http.Client, rc string, f string) (FactionLedger, error) {\n\tl := log.WithFields(log.Fields{\n\t\t\"action\": \"sotapi.GetFactionLedger\",\n\t})\n\n\tfactionBandTitle := BandTitle{\n\t\tAthenasFortune: []string{\"Legend\", \"Guardian\", \"Voyager\", \"Seeker\"},\n\t\tGoldHoarder: []string{\"Captain\", \"Marauder\", \"Seafarer\", \"Castaway\"},\n\t\tMerchantAlliance: []string{\"Admiral\", \"Commander\", \"Cadet\", \"Sailor\"},\n\t\tOrderOfSouls: []string{\"Grandee\", \"Chief\", \"Mercenary\", \"Apprentice\"},\n\t\tReapersBone: []string{\"Master\", \"Keeper\", \"Servant\", \"Follower\"},\n\t}\n\n\tvar apiUrl string\n\tapiBase := \"https://www.seaofthieves.com/api/ledger/friends/\"\n\n\tswitch f {\n\tcase \"athena\":\n\t\tapiUrl = fmt.Sprintf(\"%v%v?count=10\", apiBase, \"AthenasFortune\")\n\tcase \"hoarder\":\n\t\tapiUrl = fmt.Sprintf(\"%v%v?count=10\", apiBase, \"GoldHoarders\")\n\tcase \"merchant\":\n\t\tapiUrl = fmt.Sprintf(\"%v%v?count=10\", apiBase, \"MerchantAlliance\")\n\tcase \"order\":\n\t\tapiUrl = fmt.Sprintf(\"%v%v?count=10\", apiBase, \"OrderOfSouls\")\n\tcase \"reaper\":\n\t\tapiUrl = fmt.Sprintf(\"%v%v?count=10\", apiBase, \"ReapersBones\")\n\tdefault:\n\t\treturn FactionLedger{}, fmt.Errorf(\"Unknown faction\")\n\t}\n\n\tl.Debugf(\"Fetching user ledger position in %v faction from API...\", f)\n\tvar userApiLedger ApiLedger\n\thttpResp, err := httpclient.HttpReqGet(apiUrl, hc, &rc, nil, false)\n\tif err != nil {\n\t\treturn FactionLedger{}, err\n\t}\n\tif err := json.Unmarshal(httpResp, &userApiLedger); err != nil {\n\t\tl.Errorf(\"Failed to unmarshal API response: %v\", err)\n\t\treturn FactionLedger{}, err\n\t}\n\n\tuserFactionLedger := userApiLedger.Current.Friends.User\n\tswitch f {\n\tcase \"athena\":\n\t\tuserFactionLedger.Name = \"Athenas Fortune\"\n\t\tuserFactionLedger.BandTitle = factionBandTitle.AthenasFortune[userFactionLedger.Band]\n\tcase \"hoarder\":\n\t\tuserFactionLedger.Name = \"Gold Hoarders\"\n\t\tuserFactionLedger.BandTitle = factionBandTitle.GoldHoarder[userFactionLedger.Band]\n\tcase \"merchant\":\n\t\tuserFactionLedger.Name = \"Merchant Alliance\"\n\t\tuserFactionLedger.BandTitle = factionBandTitle.MerchantAlliance[userFactionLedger.Band]\n\tcase \"order\":\n\t\tuserFactionLedger.Name = \"Order of Souls\"\n\t\tuserFactionLedger.BandTitle = factionBandTitle.OrderOfSouls[userFactionLedger.Band]\n\tcase \"reaper\":\n\t\tuserFactionLedger.Name = \"Reaper's Bones\"\n\t\tuserFactionLedger.BandTitle = factionBandTitle.ReapersBone[userFactionLedger.Band]\n\t}\n\n\treturn userFactionLedger, nil\n}", "func (player *Athelete) Fine(amount float32) {\n\tplayer.AccountBalance -= amount\n}", "func (o *Tier) GetFamily() string {\n\tif o == nil || o.Family == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Family\n}", "func (f *Fund) Balance() int {\r\n\treturn f.balance\r\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 (o *TransactionSplit) GetForeignAmount() string {\n\tif o == nil || o.ForeignAmount.Get() == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.ForeignAmount.Get()\n}", "func (f *Fund) Balance() int {\n\treturn f.balance\n}", "func (f *Fund) Balance() int {\n\treturn f.balance\n}", "func (f *Fund) Balance() int {\n\treturn f.balance\n}", "func (_BREMICO *BREMICOCallerSession) WithdrawFeePercent() (*big.Int, error) {\n\treturn _BREMICO.Contract.WithdrawFeePercent(&_BREMICO.CallOpts)\n}", "func (m *Message) FAC() (*FAC, error) {\n\tps, err := m.Parse(\"FAC\")\n\tpst, ok := ps.(*FAC)\n\tif ok {\n\t\treturn pst, err\n\t}\n\treturn nil, err\n}", "func (m FailingFunder) Fund(ctx context.Context, req channel.FundingReq) error {\n\treturn errors.New(\"funding failed\")\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 (o *W2) GetDependentCareBenefits() string {\n\tif o == nil || o.DependentCareBenefits.Get() == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DependentCareBenefits.Get()\n}", "func (_BREMICO *BREMICOCaller) WithdrawFeePercent(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _BREMICO.contract.Call(opts, out, \"withdrawFeePercent\")\n\treturn *ret0, err\n}", "func (cg *ConsumerGroup) GetUserFacingResourceRef() *metav1.OwnerReference {\n\tfor i, or := range cg.OwnerReferences {\n\t\t// TODO hardcoded resource kinds.\n\t\tif strings.EqualFold(or.Kind, \"trigger\") ||\n\t\t\tstrings.EqualFold(or.Kind, \"kafkasource\") ||\n\t\t\tstrings.EqualFold(or.Kind, \"kafkachannel\") {\n\t\t\treturn &cg.OwnerReferences[i]\n\t\t}\n\t}\n\treturn nil\n}", "func (x ThirdPartyServiceEntity) GetAccount() accounts.AccountOutline {\n\treturn x.Account\n}", "func (m Message) UnderlyingCashAmount() (*field.UnderlyingCashAmountField, quickfix.MessageRejectError) {\n\tf := &field.UnderlyingCashAmountField{}\n\terr := m.Body.Get(f)\n\treturn f, err\n}", "func (a *Account) Funnel(id int) (*Funnel, error) {\n\tassert(a.id > 0, \"find funnel on unsaved account: %d\", a.id)\n\tf, err := a.Tx.Funnel(id)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if f.AccountID != a.ID() {\n\t\treturn nil, ErrFunnelNotFound\n\t}\n\treturn f, nil\n}", "func (inst *DeprecatedPopulateParticipationPrintingAccount) GetPayerWithRefundAccount() *ag_solanago.AccountMeta {\n\treturn inst.AccountMetaSlice[16]\n}", "func (k King) Fight() string {\n\tif k.Weapon == nil {\n\t\treturn fmt.Sprintf(\"King %s does not have any weapon, provide one !!\", k.Name)\n\t}\n\treturn fmt.Sprintf(\"King %s fights with %s\", k.Name, k.Weapon.Attack())\n}", "func (_FCToken *FCTokenCallerSession) GetBalance() (*big.Int, error) {\n\treturn _FCToken.Contract.GetBalance(&_FCToken.CallOpts)\n}", "func (e *Huobi) GetAccount() interface{} {\n\taccounts, err := services.GetAccounts()\n\tif err != nil {\n\t\te.logger.Log(constant.ERROR, \"\", 0.0, 0.0, \"GetAccount() error, \", err)\n\t\treturn false\n\t}\n\tif accounts.Status != \"ok\" {\n\t\te.logger.Log(constant.ERROR, \"\", 0.0, 0.0, \"GetAccount() error, \", accounts.ErrMsg)\n\t\treturn false\n\t}\n\taccountID := int64(-1)\n\tcount := len(accounts.Data)\n\tfor i := 0; i < count; i++ {\n\t\tactData := accounts.Data[i]\n\t\tif actData.State == \"working\" && actData.Type == \"spot\" {\n\t\t\taccountID = actData.ID\n\t\t\tbreak\n\t\t}\n\t}\n\tif accountID == -1 {\n\t\te.logger.Log(constant.ERROR, \"\", 0.0, 0.0, \"GetAccount() error, \", \"all account locked\")\n\t\treturn false\n\t}\n\tbalance, err := services.GetAccountBalance(strconv.FormatInt(accountID, 10))\n\tif err != nil {\n\t\te.logger.Log(constant.ERROR, \"\", 0.0, 0.0, \"GetAccount() error, \", err)\n\t\treturn false\n\t}\n\tif balance.Status != \"ok\" {\n\t\te.logger.Log(constant.ERROR, \"\", 0.0, 0.0, \"GetAccount() error, \", balance.ErrMsg)\n\t\treturn false\n\t}\n\tresult := make(map[string]float64)\n\tcount = len(balance.Data.List)\n\tfor i := 0; i < count; i++ {\n\t\tsubAcc := balance.Data.List[i]\n\t\tif subAcc.Type == \"trade\" {\n\t\t\tresult[strings.ToUpper(subAcc.Currency)] = conver.Float64Must(subAcc.Balance)\n\t\t} else if subAcc.Type == \"frozen\" {\n\t\t\tresult[\"Frozen\"+strings.ToUpper(subAcc.Currency)] = conver.Float64Must(subAcc.Balance)\n\t\t}\n\t}\n\t//...\n\tconfig.ACCOUNT_ID = strconv.FormatInt(accountID, 10)\n\t//...\n\treturn result\n}", "func (f *Fortune) Withdrawal(amount decimal.Decimal) {\n\tf.active = f.active.Sub(amount)\n}", "func (_BREMFactory *BREMFactoryCallerSession) WithdrawFeePercent() (*big.Int, error) {\n\treturn _BREMFactory.Contract.WithdrawFeePercent(&_BREMFactory.CallOpts)\n}", "func (_Cakevault *CakevaultCallerSession) WithdrawFee() (*big.Int, error) {\n\treturn _Cakevault.Contract.WithdrawFee(&_Cakevault.CallOpts)\n}", "func (u *User) WithdrawCash(amount int) int {\n\tif amount <= 0 {\n\t\treturn u.cash\n\t}\n\n\tif amount > u.cash {\n\t\treturn u.cash\n\t}\n\n\tu.cash -= amount\n\treturn u.cash\n}", "func (c *Client) GetFullName() string {\n\tif c != nil {\n\t\treturn fmt.Sprintf(\"%s %s\", c.GetFirstName(), c.GetLastName())\n\t}\n\treturn \"\"\n}", "func (va *ClawbackVestingAccount) clawback(ctx sdk.Context, dest sdk.AccAddress, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) error {\n\t// Compute the clawback based on the account state only, and update account\n\ttoClawBack := va.computeClawback(ctx.BlockTime().Unix())\n\tif toClawBack.IsZero() {\n\t\treturn nil\n\t}\n\taddr := va.GetAddress()\n\tbondDenom := sk.BondDenom(ctx)\n\n\t// Compute the clawback based on bank balance and delegation, and update account\n\tencumbered := va.GetVestingCoins(ctx.BlockTime())\n\tbondedAmt := sk.GetDelegatorBonded(ctx, addr)\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, addr)\n\tbonded := sdk.NewCoins(sdk.NewCoin(bondDenom, bondedAmt))\n\tunbonding := sdk.NewCoins(sdk.NewCoin(bondDenom, unbondingAmt))\n\tunbonded := bk.GetAllBalances(ctx, addr)\n\ttoClawBack = va.updateDelegation(encumbered, toClawBack, bonded, unbonding, unbonded)\n\n\t// Write now now so that the bank module sees unvested tokens are unlocked.\n\t// Note that all store writes are aborted if there is a panic, so there is\n\t// no danger in writing incomplete results.\n\tak.SetAccount(ctx, va)\n\n\t// Now that future vesting events (and associated lockup) are removed,\n\t// the balance of the account is unlocked and can be freely transferred.\n\tspendable := bk.SpendableCoins(ctx, addr)\n\ttoXfer := coinsMin(toClawBack, spendable)\n\terr := bk.SendCoins(ctx, addr, dest, toXfer)\n\tif err != nil {\n\t\treturn err // shouldn't happen, given spendable check\n\t}\n\ttoClawBack = toClawBack.Sub(toXfer)\n\n\t// We need to traverse the staking data structures to update the\n\t// vesting account bookkeeping, and to recover more funds if necessary.\n\t// Staking is the only way unvested tokens should be missing from the bank balance.\n\n\t// If we need more, transfer UnbondingDelegations.\n\twant := toClawBack.AmountOf(bondDenom)\n\tunbondings := sk.GetUnbondingDelegations(ctx, addr, math.MaxUint16)\n\tfor _, unbonding := range unbondings {\n\t\tvalAddr, err := sdk.ValAddressFromBech32(unbonding.ValidatorAddress)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\ttransferred := sk.TransferUnbonding(ctx, addr, dest, valAddr, want)\n\t\twant = want.Sub(transferred)\n\t\tif !want.IsPositive() {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// If we need more, transfer Delegations.\n\tif want.IsPositive() {\n\t\tdelegations := sk.GetDelegatorDelegations(ctx, addr, math.MaxUint16)\n\t\tfor _, delegation := range delegations {\n\t\t\tvalidatorAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err) // shouldn't happen\n\t\t\t}\n\t\t\tvalidator, found := sk.GetValidator(ctx, validatorAddr)\n\t\t\tif !found {\n\t\t\t\t// validator has been removed\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\twantShares, err := validator.SharesFromTokensTruncated(want)\n\t\t\tif err != nil {\n\t\t\t\t// validator has no tokens\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttransferredShares := sk.TransferDelegation(ctx, addr, dest, delegation.GetValidatorAddr(), wantShares)\n\t\t\t// to be conservative in what we're clawing back, round transferred shares up\n\t\t\ttransferred := validator.TokensFromSharesRoundUp(transferredShares).RoundInt()\n\t\t\twant = want.Sub(transferred)\n\t\t\tif !want.IsPositive() {\n\t\t\t\t// Could be slightly negative, due to rounding?\n\t\t\t\t// Don't think so, due to the precautions above.\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// If we've transferred everything and still haven't transferred the desired clawback amount,\n\t// then the account must have most some unvested tokens from slashing.\n\treturn nil\n}", "func (o *AUMPortfolioRisk) GetBalance() float64 {\n\tif o == nil {\n\t\tvar ret float64\n\t\treturn ret\n\t}\n\n\treturn o.Balance\n}", "func (a ArtifactSpec_Name) Family() ArtifactSpec_Name {\n\tif a.ArtifactType() == ArtifactSpec_STONE_INGREDIENT {\n\t\treturn a.CorrespondingStone()\n\t}\n\treturn a\n}", "func (_BREMFactory *BREMFactoryCaller) WithdrawFeePercent(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _BREMFactory.contract.Call(opts, out, \"withdrawFeePercent\")\n\treturn *ret0, err\n}", "func (_BREM *BREMCallerSession) WithdrawFeePercent() (*big.Int, error) {\n\treturn _BREM.Contract.WithdrawFeePercent(&_BREM.CallOpts)\n}", "func (c *Controller) getFunds() float64 {\n\treturn c.broker.GetAvailableFunds() / 10\n}", "func (x ThirdPartyServiceEntityOutline) GetAccount() accounts.AccountOutline {\n\treturn x.Account\n}", "func (o *Transfer) GetFundingAccountId() string {\n\tif o == nil || o.FundingAccountId.Get() == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn *o.FundingAccountId.Get()\n}", "func (o *W2) GetFederalIncomeTaxWithheld() string {\n\tif o == nil || o.FederalIncomeTaxWithheld.Get() == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.FederalIncomeTaxWithheld.Get()\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 (k *PrivateKey) GetFRElement() *bls.FR {\n\treturn k.PrivKey.GetFRElement()\n}", "func (_BondedECDSAKeep *BondedECDSAKeepCaller) GetMemberETHBalance(opts *bind.CallOpts, _member common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _BondedECDSAKeep.contract.Call(opts, out, \"getMemberETHBalance\", _member)\n\treturn *ret0, err\n}", "func GetFrob() (*FrobRecord, error) {\n\targs := map[string]string{\n\t\t\"api_key\": api.APIKey,\n\t}\n\n\tvar frobResponse FrobRecord\n\tunmarshal := func(body []byte) error {\n\t\treturn json.Unmarshal(body, &frobResponse)\n\t}\n\n\terr := api.GetMethod(\"rtm.auth.getFrob\", args, unmarshal)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &frobResponse, nil\n\n}", "func (o *Wireless) GetFamily() string {\n\tif o == nil || o.Family == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Family\n}", "func FundAccount(address string) error {\n\tresp, err := http.Get(\"https://friendbot.zion.info/?addr=\" + address)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"requesting friendbot lumens\")\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"reading response from bad friendbot request %d\", resp.StatusCode)\n\t\t}\n\t\treturn fmt.Errorf(\"error funding address through friendbot. got bad status code %d, response %s\", resp.StatusCode, body)\n\t}\n\treturn nil\n}", "func (_Cakevault *CakevaultCallerSession) MAXWITHDRAWFEE() (*big.Int, error) {\n\treturn _Cakevault.Contract.MAXWITHDRAWFEE(&_Cakevault.CallOpts)\n}", "func (_BREM *BREMCaller) WithdrawFeePercent(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _BREM.contract.Call(opts, out, \"withdrawFeePercent\")\n\treturn *ret0, err\n}", "func (t *TezTracker) GetAccount(id string) (acc models.AccountListView, err error) {\n\tr := t.repoProvider.GetAccount()\n\n\tfilter := models.Account{AccountID: null.StringFrom(id)}\n\n\tfound, acc, err := r.Find(filter)\n\tif err != nil {\n\t\treturn acc, err\n\t}\n\tif !found {\n\t\treturn acc, ErrNotFound\n\t}\n\n\tcounts, err := t.repoProvider.GetOperation().AccountOperationCount(acc.AccountID.String)\n\tif err != nil {\n\t\treturn acc, err\n\t}\n\n\tvar total int64\n\tfor i := range counts {\n\t\tif counts[i].Kind == \"transaction\" {\n\t\t\tacc.Transactions = counts[i].Count\n\t\t}\n\t\tif counts[i].Kind == \"reveal\" {\n\t\t\tacc.IsRevealed = true\n\t\t}\n\n\t\ttotal += counts[i].Count\n\t}\n\n\tacc.Operations = total\n\n\tbi, err := t.GetBakerInfo(id)\n\tif err != nil {\n\t\treturn acc, err\n\t}\n\n\tacc.BakerInfo = bi\n\n\t//Account identified as baker\n\tif bi != nil {\n\t\t//Set real value for front\n\t\tacc.IsBaker = true\n\t}\n\n\treturn acc, nil\n}", "func (t *TezTracker) GetAccount(id string) (acc models.AccountListView, err error) {\n\tr := t.repoProvider.GetAccount()\n\n\tfilter := models.Account{AccountID: null.StringFrom(id)}\n\n\tfound, acc, err := r.Find(filter)\n\tif err != nil {\n\t\treturn acc, err\n\t}\n\tif !found {\n\t\treturn acc, ErrNotFound\n\t}\n\n\tcounts, err := t.repoProvider.GetOperation().AccountOperationCount(acc.AccountID.String)\n\tif err != nil {\n\t\treturn acc, err\n\t}\n\n\tvar total int64\n\tfor i := range counts {\n\t\tif counts[i].Kind == \"transaction\" {\n\t\t\tacc.Transactions = counts[i].Count\n\t\t}\n\t\tif counts[i].Kind == \"reveal\" {\n\t\t\tacc.IsRevealed = true\n\t\t}\n\n\t\ttotal += counts[i].Count\n\t}\n\n\tacc.Operations = total\n\n\tbi, err := t.GetBakerInfo(id)\n\tif err != nil {\n\t\treturn acc, err\n\t}\n\n\tacc.BakerInfo = bi\n\n\t//Account identified as baker\n\tif bi != nil {\n\t\t//Set real value for front\n\t\tacc.IsBaker = true\n\t}\n\n\treturn acc, nil\n}", "func (_Cakevault *CakevaultSession) WithdrawFee() (*big.Int, error) {\n\treturn _Cakevault.Contract.WithdrawFee(&_Cakevault.CallOpts)\n}", "func (_BREMICO *BREMICOSession) WithdrawFeePercent() (*big.Int, error) {\n\treturn _BREMICO.Contract.WithdrawFeePercent(&_BREMICO.CallOpts)\n}", "func (_BREMFactory *BREMFactorySession) WithdrawFeePercent() (*big.Int, error) {\n\treturn _BREMFactory.Contract.WithdrawFeePercent(&_BREMFactory.CallOpts)\n}", "func (m Message) GetAccount(f *field.AccountField) quickfix.MessageRejectError {\n\treturn m.Body.Get(f)\n}", "func (o PartnerAccountOutput) Fingerprint() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *PartnerAccount) pulumi.StringOutput { return v.Fingerprint }).(pulumi.StringOutput)\n}", "func (k Knight) Fight() string {\n\tif k.Weapon == nil {\n\t\treturn fmt.Sprintf(\"Kight %s does not have any weapon, provide one !!\", k.Name)\n\t}\n\treturn fmt.Sprintf(\"Kight %s fights with %s\", k.Name, k.Weapon.Attack())\n}", "func (x UnavailableEntity) GetAccount() accounts.AccountOutline {\n\treturn x.Account\n}", "func (_class PIFClass) GetUUID(sessionID SessionRef, self PIFRef) (_retval string, _err error) {\n\t_method := \"PIF.get_uuid\"\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 = convertStringToGo(_method + \" -> \", _result.Value)\n\treturn\n}", "func (s *SubsetFontObj) GetFamily() string {\n\treturn s.Family\n}", "func (_BurnableToken *BurnableTokenSession) BurnForRefund(_burner common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BurnableToken.Contract.BurnForRefund(&_BurnableToken.TransactOpts, _burner, _value)\n}", "func (o SkuPtrOutput) Family() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *Sku) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Family\n\t}).(pulumi.StringPtrOutput)\n}", "func (_Cakevault *CakevaultCaller) WithdrawFee(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Cakevault.contract.Call(opts, &out, \"withdrawFee\")\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 SubAccountClient) GetSubAccountBalance(req *rest3.RequestForSubAccountBalance) (rest3.ResponseForSubAccountBalance, error) {\n\tpanic(\"implement me\")\n}", "func (_BREMToken *BREMTokenSession) BurnForRefund(_burner common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BREMToken.Contract.BurnForRefund(&_BREMToken.TransactOpts, _burner, _value)\n}", "func (_BurnableToken *BurnableTokenTransactorSession) BurnForRefund(_burner common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BurnableToken.Contract.BurnForRefund(&_BurnableToken.TransactOpts, _burner, _value)\n}", "func (m *User) GetFaxNumber()(*string) {\n return m.faxNumber\n}", "func (_FCToken *FCTokenCaller) GetBalance(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _FCToken.contract.Call(opts, &out, \"getBalance\")\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 (m Message) UnderlyingFXRate() (*field.UnderlyingFXRateField, quickfix.MessageRejectError) {\n\tf := &field.UnderlyingFXRateField{}\n\terr := m.Body.Get(f)\n\treturn f, err\n}", "func (me *XsdGoPkgHasElem_GetAccountBalance) Walk() (err error) {\n\tif fn := WalkHandlers.XsdGoPkgHasElem_GetAccountBalance; 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 err = me.GetAccountBalance.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\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 getItem(Curr string) (*ForexData, error) {\n\t// Prepare the input for the query.\n\tinput := &dynamodb.GetItemInput{\n\t\tTableName: aws.String(\"Forextable\"),\n\t\tKey: map[string]*dynamodb.AttributeValue{\n\t\t\t\"Curr\": {\n\t\t\t\tS: aws.String(Curr),\n\t\t\t},\n\t\t},\n\t}\n\n\t// Retrieving the item from DynamoDB. If no matching item is found, return nil.\n\tresult, err := db.GetItem(input)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif result.Item == nil {\n\t\treturn nil, nil\n\t}\n\n\t// The result.Item object returned has the underlying type map[string]*AttributeValue.\n\t// UnmarshalMap helper to parse this straight into the fields of a struct. Note:\n\tforexitem := new(ForexData)\n\terr = dynamodbattribute.UnmarshalMap(result.Item, forexitem)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn forexitem, nil\n}", "func (s *Service) GetWithdraw(c context.Context, dateVersion string, from, limit int) (count int, withdrawVos []*model.WithdrawVo, err error) {\n\tcount, upAccounts, err := s.UpWithdraw(c, dateVersion, from, limit)\n\tif err != nil {\n\t\tlog.Error(\"s.UpWithdraw error(%v)\", err)\n\t\treturn\n\t}\n\n\tmids := make([]int64, len(upAccounts))\n\tfor i, up := range upAccounts {\n\t\tmids[i] = up.MID\n\t}\n\n\twithdrawVos = make([]*model.WithdrawVo, 0)\n\tif len(mids) == 0 {\n\t\treturn\n\t}\n\n\tupIncomeWithdrawMap, err := s.dao.QueryUpWithdrawByMids(c, mids, dateVersion)\n\tif err != nil {\n\t\tlog.Error(\"s.dao.QueryUpWithdrawByMids error(%v)\", err)\n\t\treturn\n\t}\n\n\tfor _, up := range upAccounts {\n\t\tif upIncomeWithdraw, ok := upIncomeWithdrawMap[up.MID]; ok && upIncomeWithdraw.State == _withdrawing {\n\t\t\tvo := &model.WithdrawVo{\n\t\t\t\tMID: up.MID,\n\t\t\t\tThirdCoin: float64(up.TotalUnwithdrawIncome) * float64(0.01),\n\t\t\t\tThirdOrderNo: strconv.FormatInt(upIncomeWithdraw.ID, 10),\n\t\t\t\tCTime: time.Unix(int64(upIncomeWithdraw.CTime), 0).Format(\"2006-01-02 15:04:05\"),\n\t\t\t\tNotifyURL: \"http://up-profit.bilibili.co/allowance/api/x/internal/growup/up/withdraw/success\",\n\t\t\t}\n\n\t\t\twithdrawVos = append(withdrawVos, vo)\n\t\t}\n\t}\n\n\treturn\n}", "func (pr *ProvenAccountResource) GetBalance() uint64 {\n\tif !pr.proven {\n\t\tpanic(\"not valid proven account resource\")\n\t}\n\treturn pr.accountResource.Balance\n}", "func (o *TransactionSplit) GetForeignCurrencyCode() string {\n\tif o == nil || o.ForeignCurrencyCode.Get() == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.ForeignCurrencyCode.Get()\n}", "func (_BREMToken *BREMTokenTransactorSession) BurnForRefund(_burner common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BREMToken.Contract.BurnForRefund(&_BREMToken.TransactOpts, _burner, _value)\n}", "func (o *Object) GetTier() string {\n\tdo, ok := o.Object.(fs.GetTierer)\n\tif !ok {\n\t\treturn \"\"\n\t}\n\treturn do.GetTier()\n}", "func (o *Object) GetTier() string {\n\tdo, ok := o.Object.(fs.GetTierer)\n\tif !ok {\n\t\treturn \"\"\n\t}\n\treturn do.GetTier()\n}", "func (client *Client) GetOwnUser() (*User, error) {\n\tif len(client.bearer) < 1 {\n\t\treturn nil, errors.New(\"a bearer token is required to use this endpoint\")\n\t}\n\tusers, err := client.GetUsers(UserOpts{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(users.Data) < 1 {\n\t\treturn nil, errors.New(\"unable to get user\")\n\t}\n\tuser := users.Data[0]\n\tclient.Self = user\n\treturn &user, nil\n}", "func (x ExternalEntity) GetAccount() accounts.AccountOutline {\n\treturn x.Account\n}", "func (_Fibonacci *FibonacciCallerSession) GetFib(n *big.Int) (*big.Int, error) {\n\treturn _Fibonacci.Contract.GetFib(&_Fibonacci.CallOpts, n)\n}", "func (m Message) UnderlyingFactor() (*field.UnderlyingFactorField, quickfix.MessageRejectError) {\n\tf := &field.UnderlyingFactorField{}\n\terr := m.Body.Get(f)\n\treturn f, err\n}", "func (m Message) UnderlyingFactor() (*field.UnderlyingFactorField, quickfix.MessageRejectError) {\n\tf := &field.UnderlyingFactorField{}\n\terr := m.Body.Get(f)\n\treturn f, err\n}", "func getAffiliation(affiliation, orgName string, sdk *fabsdk.FabricSDK) (*msp.AffiliationResponse, error) {\n\tmspClient, err := msp.New(sdk.Context(), msp.WithOrg(orgName))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn mspClient.GetAffiliation(affiliation)\n}", "func (o *Tier) GetFamilyOk() (*string, bool) {\n\tif o == nil || o.Family == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Family, true\n}", "func getMember(client *chef.Client, member string) chef.User {\n\tmemberInfo, err := client.Users.Get(member)\n\tif err != nil {\n\t\tfmt.Println(\"Issue getting: \"+member, err)\n\t\tpanic(err.Error()) // proper error handling instead of panic in your app\n\t}\n\treturn memberInfo\n}", "func (_BREM *BREMSession) WithdrawFeePercent() (*big.Int, error) {\n\treturn _BREM.Contract.WithdrawFeePercent(&_BREM.CallOpts)\n}", "func (d *Dao) FavDisplay(c context.Context, mid int64) (bangumi, cinema int, err error) {\n\tip := metadata.String(c, metadata.RemoteIP)\n\tparams := url.Values{}\n\tparams.Set(\"mid\", strconv.FormatInt(mid, 10))\n\tvar res struct {\n\t\tCode int `json:\"code\"`\n\t\tResult struct {\n\t\t\tBangumi int `json:\"bangumi\"`\n\t\t\tCinema int `json:\"cinema\"`\n\t\t} `json:\"result\"`\n\t}\n\tif err = d.client.Get(c, d.favDisplay, ip, params, &res); err != nil {\n\t\treturn\n\t}\n\tif res.Code != ecode.OK.Code() {\n\t\terr = errors.Wrap(ecode.Int(res.Code), d.favDisplay+\"?\"+params.Encode())\n\t\treturn\n\t}\n\tbangumi = res.Result.Bangumi\n\tcinema = res.Result.Cinema\n\treturn\n}", "func (_Cakevault *CakevaultSession) MAXWITHDRAWFEE() (*big.Int, error) {\n\treturn _Cakevault.Contract.MAXWITHDRAWFEE(&_Cakevault.CallOpts)\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 (t *SimpleChaincode) getFinancialInstitutionDetails(stub shim.ChaincodeStubInterface, finInst string) ([]byte, error) {\n\n\tfmt.Println(\"Start find getFinancialInstitutionDetails\")\n\tfmt.Println(\"Looking for \" + finInst)\n\n\t//get the finInst index\n\tfdAsBytes, err := stub.GetState(finInst)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Failed to get Financial Institution\")\n\t}\n\n\treturn fdAsBytes, nil\n\n}", "func (client *WANPOTSLinkConfig1) GetFclass() (NewFclass string, err error) {\n\treturn client.GetFclassCtx(context.Background())\n}", "func (x UnavailableEntityOutline) GetAccount() accounts.AccountOutline {\n\treturn x.Account\n}", "func (sc Funcs) AccountNFTAmount(ctx wasmlib.ScViewClientContext) *AccountNFTAmountCall {\n\tf := &AccountNFTAmountCall{Func: wasmlib.NewScView(ctx, HScName, HViewAccountNFTAmount)}\n\tf.Params.Proxy = wasmlib.NewCallParamsProxy(f.Func)\n\twasmlib.NewCallResultsProxy(f.Func, &f.Results.Proxy)\n\treturn f\n}", "func (a *FastlyIntegrationApi) GetFastlyAccount(ctx _context.Context, accountId string) (FastlyAccountResponse, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarReturnValue FastlyAccountResponse\n\t)\n\n\tlocalBasePath, err := a.Client.Cfg.ServerURLWithContext(ctx, \"v2.FastlyIntegrationApi.GetFastlyAccount\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, datadog.GenericOpenAPIError{ErrorMessage: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/api/v2/integrations/fastly/accounts/{account_id}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"account_id\"+\"}\", _neturl.PathEscape(datadog.ParameterToString(accountId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tlocalVarHeaderParams[\"Accept\"] = \"application/json\"\n\n\tdatadog.SetAuthKeys(\n\t\tctx,\n\t\t&localVarHeaderParams,\n\t\t[2]string{\"apiKeyAuth\", \"DD-API-KEY\"},\n\t\t[2]string{\"appKeyAuth\", \"DD-APPLICATION-KEY\"},\n\t)\n\treq, err := a.Client.PrepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, nil)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.Client.CallAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := datadog.ReadBody(localVarHTTPResponse)\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := datadog.GenericOpenAPIError{\n\t\t\tErrorBody: localVarBody,\n\t\t\tErrorMessage: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 || localVarHTTPResponse.StatusCode == 403 || localVarHTTPResponse.StatusCode == 404 || localVarHTTPResponse.StatusCode == 429 {\n\t\t\tvar v APIErrorResponse\n\t\t\terr = a.Client.Decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.ErrorModel = v\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 := datadog.GenericOpenAPIError{\n\t\t\tErrorBody: localVarBody,\n\t\t\tErrorMessage: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (a *SingleAwaitility) GetKubeFedCluster(expNs string, clusterType cluster.Type, condition *v1beta1.ClusterCondition) (v1beta1.KubeFedCluster, bool, error) {\n\tclusters := &v1beta1.KubeFedClusterList{}\n\tif err := a.Client.List(context.TODO(), &client.ListOptions{Namespace: a.Ns}, clusters); err != nil {\n\t\treturn v1beta1.KubeFedCluster{}, false, err\n\t}\n\tfor _, cl := range clusters.Items {\n\t\tif cl.Labels[\"namespace\"] == expNs && cluster.Type(cl.Labels[\"type\"]) == clusterType {\n\t\t\tif containsClusterCondition(cl.Status.Conditions, condition) {\n\t\t\t\ta.T.Logf(\"found %s KubeFedCluster running in namespace '%s'\", clusterType, expNs)\n\t\t\t\treturn cl, true, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn v1beta1.KubeFedCluster{}, false, nil\n}", "func (o *AUMEvoluation) GetBalance() float64 {\n\tif o == nil {\n\t\tvar ret float64\n\t\treturn ret\n\t}\n\n\treturn o.Balance\n}", "func FFNet(url string) FfInfo {\n\tvar res FfInfo\n\tdoc, err := goquery.NewDocument(url)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tprof := doc.Find(\"div[id='profile_top']\")\n\tres.Title = prof.Find(\"b\").Text()\n\tres.Author = prof.Find(\"a\").First().Text()\t\n\tres.AuthorURL,_ = prof.Find(\"a\").First().Attr(\"href\")\n\tres.AuthorURL = strings.Join([]string{\"https://www.fanfiction.net\", res.AuthorURL}, \"\")\n\tres.Desc = prof.Find(\"div[class='xcontrast_txt']\").First().Text()\n\tres.Stats = prof.Find(\"span[class='xgray xcontrast_txt']\").First().Text()\n\n\treturn res\n}", "func (me *XHasElem_ForeName) Walk() (err error) {\n\tif fn := WalkHandlers.XHasElem_ForeName; 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 (_Cakevault *CakevaultCallerSession) WithdrawFeePeriod() (*big.Int, error) {\n\treturn _Cakevault.Contract.WithdrawFeePeriod(&_Cakevault.CallOpts)\n}", "func (m NoSides) GetAccount() (v string, err quickfix.MessageRejectError) {\n\tvar f field.AccountField\n\tif err = m.Get(&f); err == nil {\n\t\tv = f.Value()\n\t}\n\treturn\n}", "func (afric africaTimeZones) Freetown() string {return \"Africa/Freetown\" }", "func TestFundRecovery( //nolint:revive // test.Test... stutters but this is OK in this special case.\n\tctx context.Context,\n\tt *testing.T,\n\tparams FundSetup,\n\tsetup func(*rand.Rand) ([2]RoleSetup, channel.Asset),\n) {\n\trng := test.Prng(t)\n\n\tt.Run(\"failing funder proposer\", func(t *testing.T) {\n\t\troles, asset := setup(rng)\n\t\troles[0].Funder = FailingFunder{}\n\n\t\trunFredFridaTest(ctx, t, rng, params, roles, asset)\n\t})\n\n\tt.Run(\"failing funder proposee\", func(t *testing.T) {\n\t\troles, asset := setup(rng)\n\t\troles[1].Funder = FailingFunder{}\n\n\t\trunFredFridaTest(ctx, t, rng, params, roles, asset)\n\t})\n\n\tt.Run(\"failing funder both sides\", func(t *testing.T) {\n\t\troles, asset := setup(rng)\n\t\troles[0].Funder = FailingFunder{}\n\t\troles[1].Funder = FailingFunder{}\n\n\t\trunFredFridaTest(ctx, t, rng, params, roles, asset)\n\t})\n}", "func (_DevUtils *DevUtilsTransactor) GetBalance(opts *bind.TransactOpts, ownerAddress common.Address, assetData []byte) (*types.Transaction, error) {\n\treturn _DevUtils.contract.Transact(opts, \"getBalance\", ownerAddress, assetData)\n}" ]
[ "0.52361333", "0.5219271", "0.5107116", "0.49333978", "0.48144346", "0.47565222", "0.47532547", "0.46947348", "0.46947348", "0.46947348", "0.46271998", "0.46200928", "0.45988363", "0.4598473", "0.45913786", "0.4580138", "0.45723897", "0.4563494", "0.45597363", "0.45284525", "0.4526007", "0.45206016", "0.45175213", "0.45161673", "0.45069033", "0.450624", "0.44924933", "0.44722432", "0.44629595", "0.4449418", "0.44223243", "0.44178563", "0.4392868", "0.43869686", "0.4384785", "0.4384156", "0.43814567", "0.43802556", "0.43766004", "0.4374173", "0.43653074", "0.436296", "0.43593392", "0.4349146", "0.43490437", "0.43410623", "0.43396723", "0.43396723", "0.4338768", "0.4337269", "0.43348047", "0.4329167", "0.432783", "0.4323576", "0.43143478", "0.43100563", "0.4300747", "0.42969733", "0.42956355", "0.42942148", "0.4293392", "0.4277509", "0.42710158", "0.42696622", "0.4267931", "0.42678544", "0.42584097", "0.4257051", "0.42566228", "0.42499503", "0.4248918", "0.42449108", "0.42447865", "0.42447865", "0.42431274", "0.42413914", "0.42403877", "0.4239459", "0.4239459", "0.42360914", "0.42337206", "0.42253372", "0.4222151", "0.4221585", "0.42190096", "0.42152774", "0.4212886", "0.42123386", "0.42112887", "0.42067716", "0.42022982", "0.4201986", "0.41877705", "0.41794845", "0.4179112", "0.41726908", "0.41723734", "0.41716912", "0.41684014", "0.41683123" ]
0.82736015
0
GetUnlockedOnly implements the exported.ClawbackVestingAccountI interface. It returns the unlocking schedule at blockTIme. Like GetVestedCoins, but only for the lockup component.
GetUnlockedOnly реализует интерфейс exported.ClawbackVestingAccountI. Он возвращает график разблокировки по времени блока. Как GetVestedCoins, но только для компонента блокировки.
func (va ClawbackVestingAccount) GetUnlockedOnly(blockTime time.Time) sdk.Coins { return ReadSchedule(va.StartTime, va.EndTime, va.LockupPeriods, va.OriginalVesting, blockTime.Unix()) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (va ClawbackVestingAccount) GetVestedOnly(blockTime time.Time) sdk.Coins {\n\treturn ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, blockTime.Unix())\n}", "func (_Constants *ConstantsCallerSession) UnstakeLockPeriod() (*big.Int, error) {\n\treturn _Constants.Contract.UnstakeLockPeriod(&_Constants.CallOpts)\n}", "func (_Constants *ConstantsCaller) UnstakeLockPeriod(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Constants.contract.Call(opts, &out, \"unstakeLockPeriod\")\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 (_Constants *ConstantsSession) UnstakeLockPeriod() (*big.Int, error) {\n\treturn _Constants.Contract.UnstakeLockPeriod(&_Constants.CallOpts)\n}", "func (m *AndroidWorkProfileGeneralDeviceConfiguration) GetWorkProfilePasswordBlockFingerprintUnlock()(*bool) {\n return m.workProfilePasswordBlockFingerprintUnlock\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 (w *xcWallet) unlocked() bool {\n\tif w.isDisabled() {\n\t\treturn false\n\t}\n\ta, is := w.Wallet.(asset.Authenticator)\n\tif !is {\n\t\treturn w.locallyUnlocked()\n\t}\n\tif w.parent != nil {\n\t\treturn w.parent.unlocked()\n\t}\n\tif !w.connected() {\n\t\treturn false\n\t}\n\treturn w.locallyUnlocked() && !a.Locked()\n}", "func (d *Dot) UnlockedGet(key string) (interface{}, bool) {\n\t//\td.l.Lock() // protect me, and ...\n\t//\tdefer d.l.Unlock() // release me, let me go ...\n\tc := d.getChild(key)\n\treturn c, true // bool avoids usage from templates!\n}", "func (m *InformationProtection) GetBitlocker()(Bitlockerable) {\n val, err := m.GetBackingStore().Get(\"bitlocker\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(Bitlockerable)\n }\n return nil\n}", "func (o *Block) GetReadOnly(ctx context.Context) (readOnly bool, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceBlock, \"ReadOnly\").Store(&readOnly)\n\treturn\n}", "func (m *AndroidWorkProfileGeneralDeviceConfiguration) GetPasswordBlockFingerprintUnlock()(*bool) {\n return m.passwordBlockFingerprintUnlock\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 (m *AndroidWorkProfileGeneralDeviceConfiguration) GetWorkProfileBlockNotificationsWhileDeviceLocked()(*bool) {\n return m.workProfileBlockNotificationsWhileDeviceLocked\n}", "func (rt *recvTxOut) Locked() bool {\n\treturn rt.locked\n}", "func (_Onesplitaudit *OnesplitauditCallerSession) FLAGDISABLEWETH() (*big.Int, error) {\n\treturn _Onesplitaudit.Contract.FLAGDISABLEWETH(&_Onesplitaudit.CallOpts)\n}", "func (o BucketIamConfigurationBucketPolicyOnlyOutput) LockedTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketIamConfigurationBucketPolicyOnly) *string { return v.LockedTime }).(pulumi.StringPtrOutput)\n}", "func (txo *TxOutput) CanBeUnlockedWith(unlockingData string) bool {\n\treturn txo.ScriptPubKey == unlockingData\n}", "func (m *MailboxMemoryCache) GetBlocked() []Mailbox {\n\tvar result []Mailbox\n\tfor _, mailbox := range m.Data {\n\t\tif mailbox.Blocked {\n\t\t\tresult = append(result, mailbox)\n\t\t}\n\t}\n\treturn result\n}", "func (_Onesplitaudit *OnesplitauditSession) FLAGDISABLEWETH() (*big.Int, error) {\n\treturn _Onesplitaudit.Contract.FLAGDISABLEWETH(&_Onesplitaudit.CallOpts)\n}", "func (out *TxOutput) CanBeUnlocked(data string) bool {\n\treturn out.PublicKey == data\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 (_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 (_Onesplitaudit *OnesplitauditCallerSession) FLAGDISABLEKYBER() (*big.Int, error) {\n\treturn _Onesplitaudit.Contract.FLAGDISABLEKYBER(&_Onesplitaudit.CallOpts)\n}", "func (wt *Wallet) Locked() bool {\n\treturn <-wt.lockState\n}", "func (sqlStore *SQLStore) GetUnlockedClusterInstallationsPendingWork() ([]*model.ClusterInstallation, error) {\n\n\tbuilder := clusterInstallationSelect.\n\t\tWhere(sq.Eq{\n\t\t\t\"State\": model.AllClusterInstallationStatesPendingWork,\n\t\t}).\n\t\tWhere(\"LockAcquiredAt = 0\").\n\t\tOrderBy(\"CreateAt ASC\")\n\n\tvar clusterInstallations []*model.ClusterInstallation\n\terr := sqlStore.selectBuilder(sqlStore.db, &clusterInstallations, builder)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to get cluster installations pending work\")\n\t}\n\n\treturn clusterInstallations, nil\n}", "func (c *Client) RenterInactiveContractsGet() (rc api.RenterContracts, err error) {\n\tquery := fmt.Sprintf(\"?inactive=%v\", true)\n\terr = c.get(\"/renter/contracts\"+query, &rc)\n\treturn\n}", "func (pva PeriodicVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn pva.BaseVestingAccount.LockedCoinsFromVesting(pva.GetVestingCoins(ctx.BlockTime()))\n}", "func (w *rpcWallet) AccountUnlocked(ctx context.Context, acctName string) (bool, error) {\n\t// First return locked status of the account, falling back to walletinfo if\n\t// the account is not individually password protected.\n\tres, err := w.rpcClient.AccountUnlocked(ctx, acctName)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif res.Encrypted {\n\t\treturn *res.Unlocked, nil\n\t}\n\t// The account is not individually encrypted, so check wallet lock status.\n\twalletInfo, err := w.rpcClient.WalletInfo(ctx)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"walletinfo error: %w\", err)\n\t}\n\treturn walletInfo.Unlocked, nil\n}", "func (w *Wallet) Locked() bool {\n\treturn <-w.lockState\n}", "func (_Onesplitaudit *OnesplitauditSession) FLAGDISABLEKYBER() (*big.Int, error) {\n\treturn _Onesplitaudit.Contract.FLAGDISABLEKYBER(&_Onesplitaudit.CallOpts)\n}", "func (plva PermanentLockedAccount) GetVestingCoins(_ time.Time) sdk.Coins {\n\treturn plva.OriginalVesting\n}", "func (p *Policy) GetBlockedAccountsInternal(dao dao.DAO) (BlockedAccounts, error) {\n\tp.lock.RLock()\n\tdefer p.lock.RUnlock()\n\tif p.isValid {\n\t\treturn p.blockedAccounts, nil\n\t}\n\tsi := dao.GetStorageItem(p.ContractID, blockedAccountsKey)\n\tif si == nil {\n\t\treturn nil, errors.New(\"BlockedAccounts uninitialized\")\n\t}\n\tba, err := BlockedAccountsFromBytes(si.Value)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ba, nil\n}", "func (db *merkleDB) getValueWithoutLock(key path) ([]byte, error) {\n\tif db.closed {\n\t\treturn nil, database.ErrClosed\n\t}\n\n\tn, err := db.getNode(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif n.value.IsNothing() {\n\t\treturn nil, database.ErrNotFound\n\t}\n\treturn n.value.Value(), nil\n}", "func (o *DriveAta) GetSecurityFrozen(ctx context.Context) (securityFrozen bool, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDriveAta, \"SecurityFrozen\").Store(&securityFrozen)\n\treturn\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 (out *TxOutput) CanBeUnlocked(data string) bool {\n\treturn out.PubKey == data //PubKey is the data that is used in the PubKey\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 (m *AndroidWorkProfileGeneralDeviceConfiguration) GetWorkProfileBlockAddingAccounts()(*bool) {\n return m.workProfileBlockAddingAccounts\n}", "func (o BucketIamConfigurationBucketPolicyOnlyPtrOutput) LockedTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BucketIamConfigurationBucketPolicyOnly) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.LockedTime\n\t}).(pulumi.StringPtrOutput)\n}", "func testNonNilTimeoutLock(ctx context.Context, t *testing.T, w *Wallet) {\n\ttimeChan := make(chan time.Time)\n\terr := w.Unlock(ctx, testPrivPass, timeChan)\n\tif err != nil {\n\t\tt.Fatal(\"failed to unlock wallet\")\n\t}\n\ttimeChan <- time.Time{}\n\ttime.Sleep(100 * time.Millisecond) // Allow time for lock in background\n\tif !w.Locked() {\n\t\tt.Fatal(\"wallet should have locked after timeout\")\n\t}\n}", "func (_DelegationController *DelegationControllerTransactor) GetAndUpdateLockedAmount(opts *bind.TransactOpts, wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"getAndUpdateLockedAmount\", wallet)\n}", "func (_Distributor *DistributorCaller) GetAndUpdateEarnedBountyAmountReadOnly(opts *bind.CallOpts, validatorId *big.Int) error {\n\ttype Bounty struct {\n\t\tearned *big.Int\n\t\tendMonth *big.Int\n\t}\n\tvar bounty Bounty\n\terr := _Distributor.contract.Call(opts, &bounty, \"getAndUpdateEarnedBountyAmount\", validatorId)\n\treturn err\n}", "func (va ClawbackVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn va.BaseVestingAccount.LockedCoinsFromVesting(va.GetVestingCoins(ctx.BlockTime()))\n}", "func (o BucketIamConfigurationBucketPolicyOnlyResponseOutput) LockedTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v BucketIamConfigurationBucketPolicyOnlyResponse) string { return v.LockedTime }).(pulumi.StringOutput)\n}", "func (w *xcWallet) locallyUnlocked() bool {\n\tif w.isDisabled() {\n\t\treturn false\n\t}\n\tif w.parent != nil {\n\t\treturn w.parent.locallyUnlocked()\n\t}\n\tw.mtx.RLock()\n\tdefer w.mtx.RUnlock()\n\tif len(w.encPass) == 0 {\n\t\treturn true // unencrypted wallet\n\t}\n\treturn len(w.pw) > 0 // cached password for encrypted wallet\n}", "func (o BucketIamConfigurationUniformBucketLevelAccessOutput) LockedTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketIamConfigurationUniformBucketLevelAccess) *string { return v.LockedTime }).(pulumi.StringPtrOutput)\n}", "func GetUnfreezeClockDeferFunc(t *testing.T) func() {\n\treturn func() {\n\t\tr := recover()\n\t\tUnfreezeClock(t)\n\t\tif r != nil {\n\t\t\tpanic(r)\n\t\t}\n\t}\n}", "func Without(l sync.Locker, f func()) {\n\tl.Unlock()\n\tdefer l.Lock()\n\tf()\n}", "func (cli *Cli) GetFrozenTime(addr string) (int64, error) {\n\tinstance, err := ytc.NewYtc(cli.ytaContractAddr, cli.client)\n\tif err != nil {\n\t\t//log.Fatalf(\"error when create instance of yottacoin stub: %s\\n\", err.Error())\n\t\treturn 0, err\n\t}\n\ttimestamp, err := instance.GetFrozenTimestamp(nil, common.HexToAddress(addr))\n\tif err != nil {\n\t\t//log.Fatalf(\"error when get frozen timestamp of address %s: %s\\n\", addr, err.Error())\n\t\treturn 0, err\n\t}\n\treturn timestamp.Int64(), nil\n}", "func (plva PermanentLockedAccount) GetVestedCoins(_ time.Time) sdk.Coins {\n\treturn nil\n}", "func (m *OnlineMeetingInfo) GetTollFreeNumbers()([]string) {\n val, err := m.GetBackingStore().Get(\"tollFreeNumbers\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]string)\n }\n return nil\n}", "func UnfreezeClock(t *testing.T) {\n\tif t == nil {\n\t\tpanic(\"nice try\")\n\t}\n\tc = &DefaultClock{}\n}", "func TestGetLock(t *testing.T) {\n\tlockfile := lockOrFail(t)\n\tdefer removeTestLock(lockfile)\n}", "func (del Delegation) UnlockedAmount() (hexutil.Big, error) {\n\treturn repository.R().DelegationAmountUnlocked(&del.Address, (*big.Int)(del.Delegation.ToStakerId))\n}", "func (m *ManagedDeviceItemRequestBuilder) BypassActivationLock()(*if245b21847517f2bdf21fefeaac5356812b1d5b2cad61e07f1e97c61a72adfeb.BypassActivationLockRequestBuilder) {\n return if245b21847517f2bdf21fefeaac5356812b1d5b2cad61e07f1e97c61a72adfeb.NewBypassActivationLockRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func testNoNilTimeoutReplacement(ctx context.Context, t *testing.T, w *Wallet) {\n\terr := w.Unlock(ctx, testPrivPass, nil)\n\tif err != nil {\n\t\tt.Fatal(\"failed to unlock wallet\")\n\t}\n\ttimeChan := make(chan time.Time)\n\terr = w.Unlock(ctx, testPrivPass, timeChan)\n\tif err != nil {\n\t\tt.Fatal(\"failed to unlock wallet with time channel\")\n\t}\n\tselect {\n\tcase timeChan <- time.Time{}:\n\tcase <-time.After(100 * time.Millisecond):\n\t\tt.Fatal(\"time channel was not read in 100ms\")\n\t}\n\tif w.Locked() {\n\t\tt.Fatal(\"expected wallet to remain unlocked due to previous unlock without timeout\")\n\t}\n}", "func excludeByIsolation(container *container.Snapshot, ctx *listContext) iterationAction {\n\treturn includeContainer\n}", "func (_Onesplitaudit *OnesplitauditCaller) FLAGDISABLEKYBER(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Onesplitaudit.contract.Call(opts, &out, \"FLAG_DISABLE_KYBER\")\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 (r *reader) GetSurveillanceBlocking() (blocking bool, err error) {\n\t// Retro-compatibility\n\ts, err := r.envParams.GetEnv(\"BLOCK_NSA\")\n\tif err != nil {\n\t\treturn false, err\n\t} else if len(s) != 0 {\n\t\tr.logger.Warn(\"You are using the old environment variable BLOCK_NSA, please consider changing it to BLOCK_SURVEILLANCE\")\n\t\treturn r.envParams.GetOnOff(\"BLOCK_NSA\", libparams.Compulsory())\n\t}\n\treturn r.envParams.GetOnOff(\"BLOCK_SURVEILLANCE\", libparams.Default(\"off\"))\n}", "func (r *Radix) getNonBlocking() interface{} {\n\treturn r.value\n}", "func (f *FakePrivilegedProjectProvider) GetUnsecured(projectInternalName string, options *provider.ProjectGetOptions) (*kubermaticapiv1.Project, error) {\n\tif NoExistingFakeProjectID == projectInternalName {\n\t\treturn nil, createError(http.StatusNotFound, \"\")\n\t}\n\tif ForbiddenFakeProjectID == projectInternalName {\n\t\treturn nil, createError(http.StatusForbidden, \"\")\n\t}\n\n\treturn nil, nil\n}", "func WithoutBlocking(ctx context.Context) context.Context {\n\treturn context.WithValue(ctx, nonBlockingTxnCtxKey, &nonBlockingTxnOpt{})\n}", "func UnLock(worktree string) func(*types.Cmd) {\n\treturn func(g *types.Cmd) {\n\t\tg.AddOptions(\"unlock\")\n\t\tg.AddOptions(worktree)\n\t}\n}", "func getUnspent(addr string, page int) (string, error) {\n\turl := bitcoinCashAPI + \"/address/\" + addr + \"/unspent?pagesize=\" +\n\t\tstrconv.Itoa(defaultPageSize) + \"&page=\" + strconv.Itoa(page)\n\n\tres, err := http.Get(url)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif res.StatusCode != 200 {\n\t\treturn \"\", errors.New(\"request failed\")\n\t}\n\n\tcontent, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(content), nil\n}", "func (policy *ticketPolicy) OnWalletUnlocked(param *types.WalletUnLock) {\n\tif param.WalletOrTicket {\n\t\tatomic.CompareAndSwapInt32(&policy.isTicketLocked, 1, 0)\n\t\tif param.Timeout != 0 {\n\t\t\tpolicy.resetTimeout(param.Timeout)\n\t\t}\n\t}\n\t// 钱包解锁时,需要刷新,通知挖矿\n\tFlushTicket(policy.getAPI())\n}", "func (o BucketIamConfigurationUniformBucketLevelAccessPtrOutput) LockedTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BucketIamConfigurationUniformBucketLevelAccess) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.LockedTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (va ClawbackVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn va.OriginalVesting.Sub(va.GetVestedCoins(blockTime))\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 (m *DeviceEnrollmentWindowsHelloForBusinessConfiguration) GetUnlockWithBiometricsEnabled()(*bool) {\n val, err := m.GetBackingStore().Get(\"unlockWithBiometricsEnabled\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\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 (ks *CSA) Unsafe_GetUnlockedPrivateKey(pubkey crypto.PublicKey) ([]byte, error) {\n\treturn ks.keys[pubkey.String()].Unsafe_GetPrivateKey()\n}", "func (o BucketIamConfigurationUniformBucketLevelAccessResponseOutput) LockedTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v BucketIamConfigurationUniformBucketLevelAccessResponse) string { return v.LockedTime }).(pulumi.StringOutput)\n}", "func (cb *CircuitBreaker) Unblock() {\n\tcb.Lock()\n\tcb.blocked = false\n\tcb.Unlock()\n}", "func (_Onesplitaudit *OnesplitauditCaller) FLAGDISABLEWETH(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Onesplitaudit.contract.Call(opts, &out, \"FLAG_DISABLE_WETH\")\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 getWallet() walletStruct {\n\n\ts := \"START getWallet() - Gets the wallet\"\n\tlog.Debug(\"WALLET: GUTS \" + s)\n\n\ts = \"END getWallet() - Gets the wallet\"\n\tlog.Debug(\"WALLET: GUTS \" + s)\n\n\treturn wallet\n}", "func (transaction *TokenUpdateTransaction) GetFreezeKey() Key {\n\treturn transaction.freezeKey\n}", "func (dva DelayedVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn dva.BaseVestingAccount.LockedCoinsFromVesting(dva.GetVestingCoins(ctx.BlockTime()))\n}", "func (_DelegationController *DelegationControllerTransactorSession) GetAndUpdateLockedAmount(wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateLockedAmount(&_DelegationController.TransactOpts, wallet)\n}", "func (prof *Profiles) Blocked() ([]BlockedUser, error) {\n\tbody, err := prof.insta.sendSimpleRequest(urlBlockedList)\n\tif err == nil {\n\t\tresp := blockedListResp{}\n\t\terr = json.Unmarshal(body, &resp)\n\t\treturn resp.BlockedList, err\n\t}\n\treturn nil, err\n}", "func GetActiveUniformBlockiv(program uint32, uniformBlockIndex uint32, pname uint32, params *int32) {\n\tsyscall.Syscall6(gpGetActiveUniformBlockiv, 4, uintptr(program), uintptr(uniformBlockIndex), uintptr(pname), uintptr(unsafe.Pointer(params)), 0, 0)\n}", "func (m *neighborEntryRWMutex) RUnlockBypass() {\n\tm.mu.RUnlock()\n}", "func GetBlockTime(slot int64, cfg *config.Config) (types.BlockTime, error) {\n\tlog.Println(\"Getting block time...\")\n\tvar result types.BlockTime\n\tops := types.HTTPOptions{\n\t\tEndpoint: cfg.Endpoints.RPCEndpoint,\n\t\tMethod: http.MethodPost,\n\t\tBody: types.Payload{Jsonrpc: \"2.0\", Method: \"getBlockTime\", ID: 1, Params: []interface{}{slot}},\n\t}\n\n\tresp, err := HitHTTPTarget(ops)\n\tif err != nil {\n\t\tlog.Printf(\"Error while getting block time: %v\", err)\n\t\treturn result, err\n\t}\n\n\terr = json.Unmarshal(resp.Body, &result)\n\tif err != nil {\n\t\tlog.Printf(\"Error while unmarshelling block time res: %v\", err)\n\t\treturn result, err\n\t}\n\treturn result, nil\n}", "func Unlock() {\n\t// TO DO\n}", "func (w *Wallet) holdUnlock() (heldUnlock, er.R) {\n\treq := make(chan heldUnlock)\n\tw.holdUnlockRequests <- req\n\thl, ok := <-req\n\tif !ok {\n\t\t// TODO(davec): This should be defined and exported from\n\t\t// waddrmgr.\n\t\treturn nil, waddrmgr.ErrLocked.New(\"address manager is locked\", nil)\n\t}\n\treturn hl, nil\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 (_DelegationController *DelegationControllerSession) GetAndUpdateLockedAmount(wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateLockedAmount(&_DelegationController.TransactOpts, wallet)\n}", "func (p *Policy) getBlockedAccounts(ic *interop.Context, _ []stackitem.Item) stackitem.Item {\n\tba, err := p.GetBlockedAccountsInternal(ic.DAO)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn ba.ToStackItem()\n}", "func (d *Dam) Unlock() {\n\td.freeze.Unlock()\n}", "func (m *ScheduleItem) GetIsPrivate()(*bool) {\n val, err := m.GetBackingStore().Get(\"isPrivate\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}", "func (o *LocalDatabaseProvider) GetUserLockoutThreshold() int32 {\n\tif o == nil || o.UserLockoutThreshold == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.UserLockoutThreshold\n}", "func (c *Channel) Locked() *big.Int {\n\treturn c.OurState.AmountLocked()\n}", "func (m *Office365ServicesUserCounts) GetTeamsInactive()(*int64) {\n val, err := m.GetBackingStore().Get(\"teamsInactive\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*int64)\n }\n return nil\n}", "func (dva DelayedVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn dva.OriginalVesting.Sub(dva.GetVestedCoins(blockTime))\n}", "func (_Constants *ConstantsCaller) WithdrawLockPeriod(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Constants.contract.Call(opts, &out, \"withdrawLockPeriod\")\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 *PrivilegedProjectProvider) GetUnsecured(projectInternalName string, options *provider.ProjectGetOptions) (*kubermaticapiv1.Project, error) {\n\tif options == nil {\n\t\toptions = &provider.ProjectGetOptions{IncludeUninitialized: true}\n\t}\n\tproject := &kubermaticapiv1.Project{}\n\tif err := p.clientPrivileged.Get(context.Background(), ctrlruntimeclient.ObjectKey{Name: projectInternalName}, project); err != nil {\n\t\treturn nil, err\n\t}\n\tif !options.IncludeUninitialized && project.Status.Phase != kubermaticapiv1.ProjectActive {\n\t\treturn nil, kerrors.NewServiceUnavailable(\"Project is not initialized yet\")\n\t}\n\treturn project, nil\n}", "func (_TokensNetwork *TokensNetworkFilterer) FilterChannelUnlocked(opts *bind.FilterOpts, channel_identifier [][32]byte) (*TokensNetworkChannelUnlockedIterator, error) {\n\n\tvar channel_identifierRule []interface{}\n\tfor _, channel_identifierItem := range channel_identifier {\n\t\tchannel_identifierRule = append(channel_identifierRule, channel_identifierItem)\n\t}\n\n\tlogs, sub, err := _TokensNetwork.contract.FilterLogs(opts, \"ChannelUnlocked\", channel_identifierRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &TokensNetworkChannelUnlockedIterator{contract: _TokensNetwork.contract, event: \"ChannelUnlocked\", logs: logs, sub: sub}, nil\n}", "func (p *BailServiceClient) UnfreezeBail(dealerId int64, amount float64, orderId int64) (r *Bail, err error) {\n\tif err = p.sendUnfreezeBail(dealerId, amount, orderId); err != nil {\n\t\treturn\n\t}\n\treturn p.recvUnfreezeBail()\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 *Office365ServicesUserCounts) GetYammerInactive()(*int64) {\n val, err := m.GetBackingStore().Get(\"yammerInactive\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*int64)\n }\n return nil\n}", "func (del Delegation) LockedUntil() hexutil.Uint64 {\n\t// get the lock\n\tlock := del.DelegationLock()\n\tif lock == nil {\n\t\treturn hexutil.Uint64(0)\n\t}\n\n\t// return the lock release time stamp\n\treturn lock.LockedUntil\n}" ]
[ "0.67690635", "0.5902726", "0.5877758", "0.5756858", "0.5283301", "0.5265267", "0.5147104", "0.5132386", "0.5092646", "0.50746304", "0.50555545", "0.50017166", "0.49906853", "0.49503067", "0.49447116", "0.49404284", "0.4913754", "0.49131387", "0.4903401", "0.4901039", "0.49005738", "0.489135", "0.48793608", "0.48700368", "0.48635647", "0.4853582", "0.4849924", "0.48494932", "0.4841779", "0.4829426", "0.48100948", "0.4793952", "0.47920567", "0.47825015", "0.476242", "0.4756044", "0.47538084", "0.47502637", "0.47366622", "0.47205278", "0.4717631", "0.47143462", "0.47109076", "0.47079387", "0.470761", "0.4705741", "0.47021186", "0.46997285", "0.4672197", "0.46687815", "0.46662334", "0.46560487", "0.4639467", "0.46383357", "0.46241945", "0.46235907", "0.4620516", "0.46190238", "0.46170768", "0.46047163", "0.45988044", "0.4592583", "0.45886755", "0.4586585", "0.4584408", "0.45799574", "0.45770323", "0.45700407", "0.45485908", "0.45452395", "0.45414785", "0.45386648", "0.45333552", "0.45295835", "0.4528283", "0.45195046", "0.45182505", "0.45161438", "0.44972518", "0.4489341", "0.44854432", "0.44826284", "0.4481232", "0.44788578", "0.44705737", "0.4468897", "0.446855", "0.44679388", "0.44637713", "0.44636708", "0.44631022", "0.445897", "0.44522637", "0.44473958", "0.44417134", "0.4437727", "0.44331262", "0.44103894", "0.44058967", "0.4404951" ]
0.8647829
0
GetVestedOnly implements the exported.ClawbackVestingAccountI interface. It returns the vesting schedule and blockTime. Like GetVestedCoins, but only for the vesting (in the clawback sense) component.
GetVestedOnly реализует интерфейс exported.ClawbackVestingAccountI. Он возвращает расписание начисления и blockTime. Как GetVestedCoins, но только для компонента начисления (в смысле clawback).
func (va ClawbackVestingAccount) GetVestedOnly(blockTime time.Time) sdk.Coins { return ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, blockTime.Unix()) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "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) 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 (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 (pva PeriodicVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn pva.OriginalVesting.Sub(pva.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 (dva DelayedVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn dva.OriginalVesting.Sub(dva.GetVestedCoins(blockTime))\n}", "func (plva PermanentLockedAccount) GetVestedCoins(_ time.Time) sdk.Coins {\n\treturn nil\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 (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) GetUnlockedOnly(blockTime time.Time) sdk.Coins {\n\treturn ReadSchedule(va.StartTime, va.EndTime, va.LockupPeriods, va.OriginalVesting, blockTime.Unix())\n}", "func (cva ContinuousVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn cva.OriginalVesting.Sub(cva.GetVestedCoins(blockTime))\n}", "func (va ClawbackVestingAccount) GetVestingPeriods() Periods {\n\treturn va.VestingPeriods\n}", "func (pva PeriodicVestingAccount) GetVestingPeriods() Periods {\n\treturn pva.VestingPeriods\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 (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 (bva BaseVestingAccount) GetOriginalVesting() sdk.Coins {\n\treturn bva.OriginalVesting\n}", "func (_TokenVesting *TokenVestingCallerSession) VestedAmount(_token common.Address) (*big.Int, error) {\n\treturn _TokenVesting.Contract.VestedAmount(&_TokenVesting.CallOpts, _token)\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 (_TokenVesting *TokenVestingSession) VestedAmount(_token common.Address) (*big.Int, error) {\n\treturn _TokenVesting.Contract.VestedAmount(&_TokenVesting.CallOpts, _token)\n}", "func (bva BaseVestingAccount) GetDelegatedVesting() sdk.Coins {\n\treturn bva.DelegatedVesting\n}", "func (pva PeriodicVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn pva.BaseVestingAccount.LockedCoinsFromVesting(pva.GetVestingCoins(ctx.BlockTime()))\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 (_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 (va ClawbackVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn va.BaseVestingAccount.LockedCoinsFromVesting(va.GetVestingCoins(ctx.BlockTime()))\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 (_TokenVesting *TokenVestingCallerSession) VestingInfo(arg0 common.Address) (struct {\n\tVestingBeneficiary common.Address\n\tReleasedSupply *big.Int\n\tStart *big.Int\n\tDuration *big.Int\n}, error) {\n\treturn _TokenVesting.Contract.VestingInfo(&_TokenVesting.CallOpts, arg0)\n}", "func (_Token *TokenCallerSession) GetStakeDeposit() (struct {\n\tAmount *big.Int\n\tStartDate *big.Int\n\tEndDate *big.Int\n\tStartCheckpointIndex *big.Int\n\tEndCheckpointIndex *big.Int\n}, error) {\n\treturn _Token.Contract.GetStakeDeposit(&_Token.CallOpts)\n}", "func (dva DelayedVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn dva.BaseVestingAccount.LockedCoinsFromVesting(dva.GetVestingCoins(ctx.BlockTime()))\n}", "func (vva ValidatorVestingAccount) SpendableCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.BaseVestingAccount.SpendableCoinsVestingAccount(vva.GetVestingCoins(blockTime))\n}", "func (_TokenVesting *TokenVestingSession) VestingInfo(arg0 common.Address) (struct {\n\tVestingBeneficiary common.Address\n\tReleasedSupply *big.Int\n\tStart *big.Int\n\tDuration *big.Int\n}, error) {\n\treturn _TokenVesting.Contract.VestingInfo(&_TokenVesting.CallOpts, arg0)\n}", "func (_Token *TokenSession) GetStakeDeposit() (struct {\n\tAmount *big.Int\n\tStartDate *big.Int\n\tEndDate *big.Int\n\tStartCheckpointIndex *big.Int\n\tEndCheckpointIndex *big.Int\n}, error) {\n\treturn _Token.Contract.GetStakeDeposit(&_Token.CallOpts)\n}", "func (a *adapter) GetInterestedEvents() ([]*pb.Interest, error) {\n\treturn []*pb.Interest{{EventType: pb.EventType_BLOCK}}, nil\n}", "func (va ClawbackVestingAccount) GetStartTime() int64 {\n\treturn va.StartTime\n}", "func (cva ContinuousVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn cva.BaseVestingAccount.LockedCoinsFromVesting(cva.GetVestingCoins(ctx.BlockTime()))\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 (er *EventRelay) GetInterestedEvents() ([]*pb.Interest, error) {\n\tlogger.Infof(\"Returning InterestedEvents - Block & FilteredBlock.\\n\")\n\treturn []*pb.Interest{\n\t\t&pb.Interest{EventType: pb.EventType_BLOCK},\n\t\t&pb.Interest{EventType: pb.EventType_FILTEREDBLOCK},\n\t}, nil\n}", "func (pva PeriodicVestingAccount) GetStartTime() int64 {\n\treturn pva.StartTime\n}", "func (_Token *TokenCaller) GetStakeDeposit(opts *bind.CallOpts) (struct {\n\tAmount *big.Int\n\tStartDate *big.Int\n\tEndDate *big.Int\n\tStartCheckpointIndex *big.Int\n\tEndCheckpointIndex *big.Int\n}, error) {\n\tret := new(struct {\n\t\tAmount *big.Int\n\t\tStartDate *big.Int\n\t\tEndDate *big.Int\n\t\tStartCheckpointIndex *big.Int\n\t\tEndCheckpointIndex *big.Int\n\t})\n\tout := ret\n\terr := _Token.contract.Call(opts, out, \"getStakeDeposit\")\n\treturn *ret, err\n}", "func (_Cakevault *CakevaultCallerSession) LastHarvestedTime() (*big.Int, error) {\n\treturn _Cakevault.Contract.LastHarvestedTime(&_Cakevault.CallOpts)\n}", "func (_Cakevault *CakevaultSession) LastHarvestedTime() (*big.Int, error) {\n\treturn _Cakevault.Contract.LastHarvestedTime(&_Cakevault.CallOpts)\n}", "func (s *PublicSfcAPI) GetDowntime(ctx context.Context, stakerID hexutil.Uint) (map[string]interface{}, error) {\n\tblocks, period, err := s.b.GetDowntime(ctx, idx.StakerID(stakerID))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn map[string]interface{}{\n\t\t\"missedBlocks\": hexutil.Uint64(blocks),\n\t\t\"downtime\": hexutil.Uint64(period),\n\t}, nil\n}", "func LicensedAtGTE(v time.Time) predicate.Pet {\n\treturn predicate.Pet(sql.FieldGTE(FieldLicensedAt, v))\n}", "func (_Onesplitaudit *OnesplitauditCallerSession) FLAGDISABLEWETH() (*big.Int, error) {\n\treturn _Onesplitaudit.Contract.FLAGDISABLEWETH(&_Onesplitaudit.CallOpts)\n}", "func getWallet() walletStruct {\n\n\ts := \"START getWallet() - Gets the wallet\"\n\tlog.Debug(\"WALLET: GUTS \" + s)\n\n\ts = \"END getWallet() - Gets the wallet\"\n\tlog.Debug(\"WALLET: GUTS \" + s)\n\n\treturn wallet\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 (o *AllocationList) GetInvestedOk() (*float64, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.Invested, true\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 (dva DelayedVestingAccount) GetStartTime() int64 {\n\treturn 0\n}", "func (o *AllocationList) SetInvested(v float64) {\n\to.Invested = v\n}", "func (cva ContinuousVestingAccount) GetStartTime() int64 {\n\treturn cva.StartTime\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 (_TrialRulesAbstract *TrialRulesAbstractTransactor) GetWitness(opts *bind.TransactOpts, trialStatus uint8) (*types.Transaction, error) {\n\treturn _TrialRulesAbstract.contract.Transact(opts, \"getWitness\", trialStatus)\n}", "func (_Cakevault *CakevaultTransactor) InCaseTokensGetStuck(opts *bind.TransactOpts, _token common.Address) (*types.Transaction, error) {\n\treturn _Cakevault.contract.Transact(opts, \"inCaseTokensGetStuck\", _token)\n}", "func (_TokenVesting *TokenVestingCaller) VestingInfo(opts *bind.CallOpts, arg0 common.Address) (struct {\n\tVestingBeneficiary common.Address\n\tReleasedSupply *big.Int\n\tStart *big.Int\n\tDuration *big.Int\n}, error) {\n\tret := new(struct {\n\t\tVestingBeneficiary common.Address\n\t\tReleasedSupply *big.Int\n\t\tStart *big.Int\n\t\tDuration *big.Int\n\t})\n\tout := ret\n\terr := _TokenVesting.contract.Call(opts, out, \"vestingInfo\", arg0)\n\treturn *ret, err\n}", "func (_Onesplitaudit *OnesplitauditSession) FLAGDISABLEWETH() (*big.Int, error) {\n\treturn _Onesplitaudit.Contract.FLAGDISABLEWETH(&_Onesplitaudit.CallOpts)\n}", "func (_Cakevault *CakevaultCaller) LastHarvestedTime(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Cakevault.contract.Call(opts, &out, \"lastHarvestedTime\")\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 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 (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 (m *Vulnerability) GetActiveExploitsObserved()(*bool) {\n val, err := m.GetBackingStore().Get(\"activeExploitsObserved\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}", "func (plva PermanentLockedAccount) LockedCoins(_ sdk.Context) sdk.Coins {\n\treturn plva.BaseVestingAccount.LockedCoinsFromVesting(plva.OriginalVesting)\n}", "func (_Contracts *ContractsCaller) GetEligibleVoters(opts *bind.CallOpts, _proposal *big.Int, _voterAddr common.Address) (struct {\n\tVoterId *big.Int\n\tVoterAddr common.Address\n\tPositionId *big.Int\n\tIsVerified bool\n\tIsVoted bool\n}, error) {\n\tret := new(struct {\n\t\tVoterId *big.Int\n\t\tVoterAddr common.Address\n\t\tPositionId *big.Int\n\t\tIsVerified bool\n\t\tIsVoted bool\n\t})\n\tout := ret\n\terr := _Contracts.contract.Call(opts, out, \"getEligibleVoters\", _proposal, _voterAddr)\n\treturn *ret, err\n}", "func (_Contracts *ContractsCallerSession) GetEligibleVoters(_proposal *big.Int, _voterAddr common.Address) (struct {\n\tVoterId *big.Int\n\tVoterAddr common.Address\n\tPositionId *big.Int\n\tIsVerified bool\n\tIsVoted bool\n}, error) {\n\treturn _Contracts.Contract.GetEligibleVoters(&_Contracts.CallOpts, _proposal, _voterAddr)\n}", "func (_Onesplitaudit *OnesplitauditCallerSession) FLAGDISABLEKYBER() (*big.Int, error) {\n\treturn _Onesplitaudit.Contract.FLAGDISABLEKYBER(&_Onesplitaudit.CallOpts)\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 (c *TestClient) GetGuestAttributes(project, zone, name, queryPath, variableKey string) (*compute.GuestAttributes, error) {\n\tif c.GetGuestAttributesFn != nil {\n\t\treturn c.GetGuestAttributesFn(project, zone, name, queryPath, variableKey)\n\t}\n\treturn c.client.GetGuestAttributes(project, zone, name, queryPath, variableKey)\n}", "func (_Cakevault *CakevaultSession) Harvest() (*types.Transaction, error) {\n\treturn _Cakevault.Contract.Harvest(&_Cakevault.TransactOpts)\n}", "func (_Cakevault *CakevaultTransactorSession) Harvest() (*types.Transaction, error) {\n\treturn _Cakevault.Contract.Harvest(&_Cakevault.TransactOpts)\n}", "func (r Virtual_ReservedCapacityGroup_Instance) GetGuest() (resp datatypes.Virtual_Guest, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_ReservedCapacityGroup_Instance\", \"getGuest\", nil, &r.Options, &resp)\n\treturn\n}", "func (_Distributor *DistributorCaller) GetAndUpdateEarnedBountyAmountReadOnly(opts *bind.CallOpts, validatorId *big.Int) error {\n\ttype Bounty struct {\n\t\tearned *big.Int\n\t\tendMonth *big.Int\n\t}\n\tvar bounty Bounty\n\terr := _Distributor.contract.Call(opts, &bounty, \"getAndUpdateEarnedBountyAmount\", validatorId)\n\treturn err\n}", "func (_Onesplitaudit *OnesplitauditSession) FLAGDISABLEKYBER() (*big.Int, error) {\n\treturn _Onesplitaudit.Contract.FLAGDISABLEKYBER(&_Onesplitaudit.CallOpts)\n}", "func harvest(ctx iscp.Sandbox) (dict.Dict, error) {\n\ta := assert.NewAssert(ctx.Log())\n\ta.RequireChainOwner(ctx, \"harvest\")\n\n\tstate := ctx.State()\n\tmustCheckLedger(state, \"accounts.withdraw.begin\")\n\tdefer mustCheckLedger(state, \"accounts.withdraw.exit\")\n\n\tpar := kvdecoder.New(ctx.Params(), ctx.Log())\n\t// if ParamWithdrawAmount > 0, take it as exact amount to withdraw\n\t// otherwise assume harvest all\n\tamount, err := par.GetUint64(ParamWithdrawAmount)\n\tharvestAll := true\n\tif err == nil && amount > 0 {\n\t\tharvestAll = false\n\t}\n\t// if dummyColor not specified and amount is specified, default is harvest specified amount of iotas\n\tcol := par.MustGetColor(ParamWithdrawColor, colored.IOTA)\n\n\tsourceAccount := commonaccount.Get(ctx.ChainID())\n\tbals, ok := GetAccountBalances(state, sourceAccount)\n\tif !ok {\n\t\t// empty balance, nothing to withdraw\n\t\treturn nil, nil\n\t}\n\ttokensToSend := bals\n\tif !harvestAll {\n\t\tbalCol := bals[col]\n\t\ta.Require(balCol >= amount, \"accounts.harvest.error: not enough tokens\")\n\t\ttokensToSend = colored.NewBalancesForColor(col, amount)\n\t}\n\ta.Require(MoveBetweenAccounts(state, sourceAccount, ctx.Caller(), tokensToSend),\n\t\t\"accounts.harvest.inconsistency. failed to move tokens to owner's account\")\n\treturn nil, nil\n}", "func GetBlockTime(chain uint64) uint64 {\n\tvar pStat BaseInfo\n\tgetDataFormDB(chain, dbStat{}, []byte{StatBaseInfo}, &pStat)\n\treturn pStat.Time\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 (p *ClockPolicy) Victim() CacheKey {\n\tvar victimKey CacheKey\n\tvar nodeItem *ClockItem\n\tfor {\n\t\tcurrentNode := (*p.clockHand)\n\t\tnodeItem = currentNode.Value.(*ClockItem)\n\t\tif nodeItem.bit {\n\t\t\tnodeItem.bit = false\n\t\t\tcurrentNode.Value = nodeItem\n\t\t\tp.clockHand = currentNode.Next()\n\t\t} else {\n\t\t\tvictimKey = nodeItem.key\n\t\t\tp.list.Move(p.clockHand.Prev())\n\t\t\tp.clockHand = nil\n\t\t\tp.list.Remove(&currentNode)\n\t\t\tdelete(p.keyNode, victimKey)\n\t\t\treturn victimKey\n\t\t}\n\t}\n}", "func (a *adapter) GetInterestedEvents() ([]*pb.Interest, error) {\n\tif a.chaincodeID != \"\" {\n\t\treturn []*pb.Interest{\n\t\t\t{EventType: pb.EventType_BLOCK},\n\t\t\t{EventType: pb.EventType_REJECTION},\n\t\t\t{EventType: pb.EventType_CHAINCODE,\n\t\t\t\tRegInfo: &pb.Interest_ChaincodeRegInfo{\n\t\t\t\t\tChaincodeRegInfo: &pb.ChaincodeReg{\n\t\t\t\t\t\tChaincodeID: a.chaincodeID,\n\t\t\t\t\t\tEventName: \"\"}}}}, nil\n\t}\n\treturn []*pb.Interest{{EventType: pb.EventType_BLOCK}, {EventType: pb.EventType_REJECTION}}, nil\n}", "func (c *PartorderClient) Get(ctx context.Context, id int) (*Partorder, error) {\n\treturn c.Query().Where(partorder.ID(id)).Only(ctx)\n}", "func (r Virtual_Guest) GetActiveTransaction() (resp datatypes.Provisioning_Version1_Transaction, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getActiveTransaction\", nil, &r.Options, &resp)\n\treturn\n}", "func (_DelegationController *DelegationControllerTransactorSession) GetAndUpdateLockedAmount(wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateLockedAmount(&_DelegationController.TransactOpts, wallet)\n}", "func (_TrialRulesAbstract *TrialRulesAbstractTransactorSession) GetWitness(trialStatus uint8) (*types.Transaction, error) {\n\treturn _TrialRulesAbstract.Contract.GetWitness(&_TrialRulesAbstract.TransactOpts, trialStatus)\n}", "func (o *Drive) GetSeat(ctx context.Context) (seat string, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"Seat\").Store(&seat)\n\treturn\n}", "func (_Cakevault *CakevaultTransactor) Harvest(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _Cakevault.contract.Transact(opts, \"harvest\")\n}", "func (g *Graph) FindEligibleCritical(difficulty byte) *Transaction {\n\tvar pending []*sortBySeedTX\n\tvar critical *Transaction\n\n\tg.Lock()\n\n\tg.seedIndex.Ascend(func(i btree.Item) bool {\n\t\ttx := i.(*sortBySeedTX)\n\n\t\tif tx.Depth <= g.rootDepth {\n\t\t\tpending = append(pending, tx)\n\t\t\treturn true\n\t\t}\n\n\t\tif !(*Transaction)(tx).IsCritical(difficulty) {\n\t\t\tpending = append(pending, tx)\n\t\t\treturn true\n\t\t}\n\n\t\tcritical = (*Transaction)(tx)\n\n\t\treturn false\n\t})\n\n\tfor _, i := range pending {\n\t\tg.seedIndex.Delete(i)\n\t}\n\n\tg.Unlock()\n\n\treturn critical\n}", "func (_Crowdsale *CrowdsaleCallerSession) SoftCapEth() (*big.Int, error) {\n\treturn _Crowdsale.Contract.SoftCapEth(&_Crowdsale.CallOpts)\n}", "func GetGuest(c *gin.Context) *group.Guest {\n\treturn c.MustGet(\"guest\").(*group.Guest)\n}", "func (r Virtual_Guest) GetBlockCancelBecauseDisconnectedFlag() (resp bool, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getBlockCancelBecauseDisconnectedFlag\", nil, &r.Options, &resp)\n\treturn\n}", "func (x *ValidatorParticipation) GetEligibleEther() uint64 {\n\tif x != nil {\n\t\treturn x.EligibleEther\n\t}\n\treturn 0\n}", "func (_DelegationController *DelegationControllerTransactor) GetAndUpdateLockedAmount(opts *bind.TransactOpts, wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"getAndUpdateLockedAmount\", wallet)\n}", "func (_BaseContentSpace *BaseContentSpaceFilterer) FilterGetAccessWallet(opts *bind.FilterOpts) (*BaseContentSpaceGetAccessWalletIterator, error) {\n\n\tlogs, sub, err := _BaseContentSpace.contract.FilterLogs(opts, \"GetAccessWallet\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &BaseContentSpaceGetAccessWalletIterator{contract: _BaseContentSpace.contract, event: \"GetAccessWallet\", logs: logs, sub: sub}, nil\n}", "func (c *Client) RenterInactiveContractsGet() (rc api.RenterContracts, err error) {\n\tquery := fmt.Sprintf(\"?inactive=%v\", true)\n\terr = c.get(\"/renter/contracts\"+query, &rc)\n\treturn\n}", "func (_IUniswapV2Pair *IUniswapV2PairCallerSession) GetReserves() (struct {\r\n\tReserve0 *big.Int\r\n\tReserve1 *big.Int\r\n\tBlockTimestampLast uint32\r\n}, error) {\r\n\treturn _IUniswapV2Pair.Contract.GetReserves(&_IUniswapV2Pair.CallOpts)\r\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}", "func (w *Wallet) Balance() Shivcoin {\n\treturn w.balance\n}", "func (_SingleAuto *SingleAutoTransactor) InCaseTokensGetStuck(opts *bind.TransactOpts, _token common.Address, _amount *big.Int) (*types.Transaction, error) {\n\treturn _SingleAuto.contract.Transact(opts, \"inCaseTokensGetStuck\", _token, _amount)\n}", "func (m MarketDataSnapshotFullRefresh) GetTotalVolumeTraded() (v decimal.Decimal, err quickfix.MessageRejectError) {\n\tvar f field.TotalVolumeTradedField\n\tif err = m.Get(&f); err == nil {\n\t\tv = f.Value()\n\t}\n\treturn\n}", "func GetBlockTime(slot int64, cfg *config.Config) (types.BlockTime, error) {\n\tlog.Println(\"Getting block time...\")\n\tvar result types.BlockTime\n\tops := types.HTTPOptions{\n\t\tEndpoint: cfg.Endpoints.RPCEndpoint,\n\t\tMethod: http.MethodPost,\n\t\tBody: types.Payload{Jsonrpc: \"2.0\", Method: \"getBlockTime\", ID: 1, Params: []interface{}{slot}},\n\t}\n\n\tresp, err := HitHTTPTarget(ops)\n\tif err != nil {\n\t\tlog.Printf(\"Error while getting block time: %v\", err)\n\t\treturn result, err\n\t}\n\n\terr = json.Unmarshal(resp.Body, &result)\n\tif err != nil {\n\t\tlog.Printf(\"Error while unmarshelling block time res: %v\", err)\n\t\treturn result, err\n\t}\n\treturn result, nil\n}", "func (c *Channel) Locked() *big.Int {\n\treturn c.OurState.AmountLocked()\n}", "func (_Crowdsale *CrowdsaleSession) SoftCapEth() (*big.Int, error) {\n\treturn _Crowdsale.Contract.SoftCapEth(&_Crowdsale.CallOpts)\n}", "func GoVet() error { return mageextras.GoVetShadow() }" ]
[ "0.67785037", "0.67503226", "0.66144603", "0.6596947", "0.65359217", "0.6487381", "0.64839846", "0.64474326", "0.64271235", "0.64212775", "0.6202558", "0.61998135", "0.6146275", "0.5791093", "0.52322394", "0.50997275", "0.5037106", "0.5030548", "0.49749142", "0.49297792", "0.4850394", "0.4826826", "0.48186716", "0.4778215", "0.47771907", "0.47614315", "0.47485176", "0.45306152", "0.45206457", "0.45144087", "0.45083815", "0.44658473", "0.44457582", "0.44181493", "0.44095033", "0.4406303", "0.42371973", "0.42295703", "0.42082724", "0.41976905", "0.4174322", "0.41733423", "0.41671607", "0.4157489", "0.4156242", "0.41466704", "0.41441852", "0.4143005", "0.41401413", "0.4124294", "0.4120631", "0.4119975", "0.41163003", "0.4110513", "0.41049707", "0.40868425", "0.4079489", "0.40732512", "0.4067565", "0.4059058", "0.40540963", "0.4053563", "0.4038872", "0.4031694", "0.4011384", "0.39803436", "0.3961656", "0.3954626", "0.39533064", "0.39491567", "0.3946973", "0.39447957", "0.39288107", "0.39186966", "0.39009076", "0.389847", "0.38824442", "0.38725668", "0.38693336", "0.3852837", "0.38506177", "0.38494286", "0.384712", "0.38459203", "0.38451993", "0.38430762", "0.38424253", "0.3837632", "0.38371766", "0.3835657", "0.38352433", "0.38344082", "0.38268152", "0.38246965", "0.38203377", "0.3818424", "0.38151017", "0.38134283", "0.38077626", "0.38063157" ]
0.8709211
0
computeClawback removes all future vesting events from the account, returns the total sum of these events. When removing the future vesting events, the lockup schedule will also have to be capped to keep the total sums the same. (But future unlocking events might be preserved if they unlock currently vested coins.) If the amount returned is zero, then the returned account should be unchanged. Does not adjust DelegatedVesting
computeClawback удаляет все будущие события прокачки из аккаунта, возвращает общую сумму этих событий. При удалении будущих событий прокачки расписание блокировки также должно быть ограничено, чтобы общая сумма осталась неизменной. (Однако будущие события разблокировки могут быть сохранены, если они разблокируют уже прокачанные монеты.) Если возвращаемая сумма равна нулю, то возвращаемый аккаунт должен остаться без изменений. Не изменяет DelegatedVesting
func (va *ClawbackVestingAccount) computeClawback(clawbackTime int64) sdk.Coins { // Compute the truncated vesting schedule and amounts. // Work with the schedule as the primary data and recompute derived fields, e.g. OriginalVesting. vestTime := va.StartTime totalVested := sdk.NewCoins() totalUnvested := sdk.NewCoins() unvestedIdx := 0 for i, period := range va.VestingPeriods { vestTime += period.Length // tie in time goes to clawback if vestTime < clawbackTime { totalVested = totalVested.Add(period.Amount...) unvestedIdx = i + 1 } else { totalUnvested = totalUnvested.Add(period.Amount...) } } lastVestTime := vestTime newVestingPeriods := va.VestingPeriods[:unvestedIdx] // To cap the unlocking schedule to the new total vested, conjunct with a limiting schedule capPeriods := []Period{ { Length: 0, Amount: totalVested, }, } _, lastLockTime, newLockupPeriods := ConjunctPeriods(va.StartTime, va.StartTime, va.LockupPeriods, capPeriods) // Now construct the new account state va.OriginalVesting = totalVested va.EndTime = max64(lastVestTime, lastLockTime) va.LockupPeriods = newLockupPeriods va.VestingPeriods = newVestingPeriods // DelegatedVesting and DelegatedFree will be adjusted elsewhere return totalUnvested }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (va *ClawbackVestingAccount) clawback(ctx sdk.Context, dest sdk.AccAddress, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) error {\n\t// Compute the clawback based on the account state only, and update account\n\ttoClawBack := va.computeClawback(ctx.BlockTime().Unix())\n\tif toClawBack.IsZero() {\n\t\treturn nil\n\t}\n\taddr := va.GetAddress()\n\tbondDenom := sk.BondDenom(ctx)\n\n\t// Compute the clawback based on bank balance and delegation, and update account\n\tencumbered := va.GetVestingCoins(ctx.BlockTime())\n\tbondedAmt := sk.GetDelegatorBonded(ctx, addr)\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, addr)\n\tbonded := sdk.NewCoins(sdk.NewCoin(bondDenom, bondedAmt))\n\tunbonding := sdk.NewCoins(sdk.NewCoin(bondDenom, unbondingAmt))\n\tunbonded := bk.GetAllBalances(ctx, addr)\n\ttoClawBack = va.updateDelegation(encumbered, toClawBack, bonded, unbonding, unbonded)\n\n\t// Write now now so that the bank module sees unvested tokens are unlocked.\n\t// Note that all store writes are aborted if there is a panic, so there is\n\t// no danger in writing incomplete results.\n\tak.SetAccount(ctx, va)\n\n\t// Now that future vesting events (and associated lockup) are removed,\n\t// the balance of the account is unlocked and can be freely transferred.\n\tspendable := bk.SpendableCoins(ctx, addr)\n\ttoXfer := coinsMin(toClawBack, spendable)\n\terr := bk.SendCoins(ctx, addr, dest, toXfer)\n\tif err != nil {\n\t\treturn err // shouldn't happen, given spendable check\n\t}\n\ttoClawBack = toClawBack.Sub(toXfer)\n\n\t// We need to traverse the staking data structures to update the\n\t// vesting account bookkeeping, and to recover more funds if necessary.\n\t// Staking is the only way unvested tokens should be missing from the bank balance.\n\n\t// If we need more, transfer UnbondingDelegations.\n\twant := toClawBack.AmountOf(bondDenom)\n\tunbondings := sk.GetUnbondingDelegations(ctx, addr, math.MaxUint16)\n\tfor _, unbonding := range unbondings {\n\t\tvalAddr, err := sdk.ValAddressFromBech32(unbonding.ValidatorAddress)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\ttransferred := sk.TransferUnbonding(ctx, addr, dest, valAddr, want)\n\t\twant = want.Sub(transferred)\n\t\tif !want.IsPositive() {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// If we need more, transfer Delegations.\n\tif want.IsPositive() {\n\t\tdelegations := sk.GetDelegatorDelegations(ctx, addr, math.MaxUint16)\n\t\tfor _, delegation := range delegations {\n\t\t\tvalidatorAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err) // shouldn't happen\n\t\t\t}\n\t\t\tvalidator, found := sk.GetValidator(ctx, validatorAddr)\n\t\t\tif !found {\n\t\t\t\t// validator has been removed\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\twantShares, err := validator.SharesFromTokensTruncated(want)\n\t\t\tif err != nil {\n\t\t\t\t// validator has no tokens\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttransferredShares := sk.TransferDelegation(ctx, addr, dest, delegation.GetValidatorAddr(), wantShares)\n\t\t\t// to be conservative in what we're clawing back, round transferred shares up\n\t\t\ttransferred := validator.TokensFromSharesRoundUp(transferredShares).RoundInt()\n\t\t\twant = want.Sub(transferred)\n\t\t\tif !want.IsPositive() {\n\t\t\t\t// Could be slightly negative, due to rounding?\n\t\t\t\t// Don't think so, due to the precautions above.\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// If we've transferred everything and still haven't transferred the desired clawback amount,\n\t// then the account must have most some unvested tokens from slashing.\n\treturn nil\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 (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 (t *TDigest) Decay(decayValue, decayLimit float64) {\n\tt.processIt(false) // don't update cumulative as we'll do that below inline\n\tvar weight float64\n\tvar remove []int\n\tt.cumulative = t.cumulative[:0]\n\tprev := 0.0\n\n\tmin := t.processed[0].Mean\n\tmax := t.processed[len(t.processed)-1].Mean\n\n\tfor i := range t.processed {\n\t\tc := &t.processed[i]\n\t\tc.Weight *= decayValue\n\t\tif c.Weight < decayLimit {\n\t\t\tremove = append(remove, i)\n\t\t} else {\n\t\t\tweight += c.Weight\n\t\t\t// do cumulative work inline\n\t\t\tt.cumulative = append(t.cumulative, prev+c.Weight/2.0)\n\t\t\tprev += c.Weight\n\t\t}\n\t}\n\tt.cumulative = append(t.cumulative, prev)\n\n\tif len(remove) > 0 {\n\t\tfor i, c := range remove {\n\t\t\tcalculated := c - i\n\t\t\tt.processed = append(t.processed[:calculated], t.processed[calculated+1:]...)\n\t\t}\n\t\tif len(t.processed) > 0 {\n\t\t\t// only set these if we've removed those centroids\n\t\t\tif min != t.processed[0].Mean {\n\t\t\t\tt.min = t.processed[0].Mean\n\t\t\t}\n\t\t\tif max != t.processed[len(t.processed)-1].Mean {\n\t\t\t\tt.max = t.processed[len(t.processed)-1].Mean\n\t\t\t}\n\t\t} else {\n\t\t\tt.min = math.MaxFloat64\n\t\t\tt.max = -math.MaxFloat64\n\t\t}\n\t}\n\n\tt.processedWeight = weight\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 (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) postReward(ctx sdk.Context, reward sdk.Coins, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) {\n\t// Find the scheduled amount of vested and unvested staking tokens\n\tbondDenom := sk.BondDenom(ctx)\n\tvested := ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, ctx.BlockTime().Unix()).AmountOf(bondDenom)\n\tunvested := va.OriginalVesting.AmountOf(bondDenom).Sub(vested)\n\n\tif unvested.IsZero() {\n\t\t// no need to adjust the vesting schedule\n\t\treturn\n\t}\n\n\tif vested.IsZero() {\n\t\t// all staked tokens must be unvested\n\t\tva.distributeReward(ctx, ak, bondDenom, reward)\n\t\treturn\n\t}\n\n\t// Find current split of account balance on staking axis\n\tbonded := sk.GetDelegatorBonded(ctx, va.GetAddress())\n\tunbonding := sk.GetDelegatorUnbonding(ctx, va.GetAddress())\n\tdelegated := bonded.Add(unbonding)\n\n\t// discover what has been slashed and remove from delegated amount\n\toldDelegated := va.DelegatedVesting.AmountOf(bondDenom).Add(va.DelegatedFree.AmountOf(bondDenom))\n\tslashed := oldDelegated.Sub(intMin(oldDelegated, delegated))\n\tdelegated = delegated.Sub(intMin(delegated, slashed))\n\n\t// Prefer delegated tokens to be unvested\n\tunvested = intMin(unvested, delegated)\n\tvested = delegated.Sub(unvested)\n\n\t// Compute the unvested amount of reward and add to vesting schedule\n\tif unvested.IsZero() {\n\t\treturn\n\t}\n\tif vested.IsZero() {\n\t\tva.distributeReward(ctx, ak, bondDenom, reward)\n\t\treturn\n\t}\n\tunvestedRatio := unvested.ToDec().QuoTruncate(bonded.ToDec()) // round down\n\tunvestedReward := scaleCoins(reward, unvestedRatio)\n\tva.distributeReward(ctx, ak, bondDenom, unvestedReward)\n}", "func (va ClawbackVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn va.OriginalVesting.Sub(va.GetVestedCoins(blockTime))\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 TotalStaked(ctx contract.StaticContext, bootstrapNodes map[string]bool) (*types.BigUInt, error) {\n\tvalidatorStats, err := getValidatorStatistics(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstatistics := map[string]*ValidatorStatistic{}\n\tfor _, statistic := range validatorStats {\n\t\tnodeAddr := loom.UnmarshalAddressPB(statistic.Address)\n\t\tif _, ok := bootstrapNodes[strings.ToLower(nodeAddr.String())]; !ok {\n\t\t\tstatistics[statistic.Address.String()] = statistic\n\t\t}\n\t}\n\n\tcandidateList := map[string]bool{}\n\tcandidates, err := LoadCandidateList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, candidate := range candidates {\n\t\tcandidateAddr := loom.UnmarshalAddressPB(candidate.Address)\n\t\tif _, ok := bootstrapNodes[strings.ToLower(candidateAddr.String())]; !ok {\n\t\t\tcandidateList[candidate.Address.String()] = true\n\t\t}\n\t}\n\n\tdelegationList, err := loadDelegationList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttotalStaked := &types.BigUInt{Value: *loom.NewBigUIntFromInt(0)}\n\t// Sum all delegations\n\tfor _, d := range delegationList {\n\t\tif _, ok := candidateList[d.Validator.String()]; ok {\n\t\t\tdelegation, err := GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\t\tif err == contract.ErrNotFound {\n\t\t\t\tcontinue\n\t\t\t} else if err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\ttotalStaked.Value.Add(&totalStaked.Value, &delegation.Amount.Value)\n\t\t}\n\t}\n\t// Sum all whitelist amounts of validators except bootstrap validators\n\tfor _, candidate := range candidates {\n\t\tif statistic, ok := statistics[candidate.Address.String()]; ok {\n\t\t\tif statistic.WhitelistAmount != nil {\n\t\t\t\ttotalStaked.Value.Add(&totalStaked.Value, &statistic.WhitelistAmount.Value)\n\t\t\t}\n\t\t}\n\t}\n\treturn totalStaked, nil\n}", "func (_Cakevault *CakevaultCaller) CalculateTotalPendingCakeRewards(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Cakevault.contract.Call(opts, &out, \"calculateTotalPendingCakeRewards\")\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 (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 (_Cakevault *CakevaultSession) CalculateTotalPendingCakeRewards() (*big.Int, error) {\n\treturn _Cakevault.Contract.CalculateTotalPendingCakeRewards(&_Cakevault.CallOpts)\n}", "func (_Cakevault *CakevaultCallerSession) CalculateTotalPendingCakeRewards() (*big.Int, error) {\n\treturn _Cakevault.Contract.CalculateTotalPendingCakeRewards(&_Cakevault.CallOpts)\n}", "func (sch *Scheduler) CalClusterBalance(podUsed *[PHYNUM][DIMENSION]float64, podReq []PodRequest) {\n\t//cal the pod sum and used rate\n\tpodLen := len(podReq)\n\tvar podNum [PHYNUM]int\n\tvar podSum int\n\tfor i := 0; i < podLen; i++ {\n\t\tif podReq[i].nodeName != -1 {\n\t\t\tpodSum++\n\t\t\tpodNum[podReq[i].nodeName]++\n\t\t}\n\t}\n\n\tvar podIdle [PHYNUM]float64\n\tvar resIdle [PHYNUM][DIMENSION]float64\n\tvar podVal float64\n\tvar resVal [DIMENSION]float64 // cal the sum and mean value\n\n\tfor i := 0; i < PHYNUM; i++ {\n\t\tpodIdle[i] = 1.0 - (float64)(podNum[i])/(float64)(podSum)\n\t\tpodVal = podVal + podIdle[i]\n\t\tfor j := 0; j < DIMENSION; j++ {\n\t\t\tresIdle[i][j] = (sch.reTotal[j] - podUsed[i][j]) / sch.reTotal[j]\n\t\t\tresVal[j] = resVal[j] + resIdle[i][j]\n\t\t}\n\t}\n\t// cal the balance value\n\tpodMean := podVal / (float64)(podSum)\n\tvar resMean [DIMENSION]float64\n\tfor j := 0; j < DIMENSION; j++ {\n\t\tresMean[j] = resVal[j] / (float64)(PHYNUM)\n\t}\n\tvar baIdle float64\n\tfor i := 0; i < PHYNUM; i++ {\n\t\tfor j := 0; j < DIMENSION; j++ {\n\t\t\tbaIdle = baIdle + math.Pow((resIdle[i][j]-resMean[j]), 2)\n\t\t}\n\t\tbaIdle = baIdle + math.Pow((podIdle[i]-podMean), 2)\n\t}\n\tbaIdle = math.Sqrt(baIdle)\n\tfmt.Printf(\"The balance value is %.3f \\n\", baIdle)\n}", "func CalculateAllTotalPayout(delegatedContracts []DelegatedContract) []DelegatedContract{\n for index, delegatedContract := range delegatedContracts{\n delegatedContracts[index] = CalculateTotalPayout(delegatedContract)\n }\n\n return delegatedContracts\n}", "func getBalanceTotal(recordCollection []record) (totalBalance time.Duration) {\n\tfor _, r := range recordCollection {\n\t\t_, balance := getWorkedHours(&r)\n\t\ttotalBalance += balance\n\t}\n\treturn totalBalance\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 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 (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 applyCliff(events []event, cliff time.Time) ([]event, error) {\n\tnewEvents := []event{}\n\tcoins := sdk.NewCoins()\n\tfor _, e := range events {\n\t\tif !e.Time.After(cliff) {\n\t\t\tcoins = coins.Add(e.Coins...)\n\t\t\tcontinue\n\t\t}\n\t\tif !coins.IsZero() {\n\t\t\tcliffEvent := event{Time: cliff, Coins: coins}\n\t\t\tnewEvents = append(newEvents, cliffEvent)\n\t\t\tcoins = sdk.NewCoins()\n\t\t}\n\t\tnewEvents = append(newEvents, e)\n\t}\n\tif !coins.IsZero() {\n\t\t// special case if all events are before the cliff\n\t\tcliffEvent := event{Time: cliff, Coins: coins}\n\t\tnewEvents = append(newEvents, cliffEvent)\n\t}\n\t// integrity check\n\toldTotal := sdk.NewCoins()\n\tfor _, e := range events {\n\t\toldTotal = oldTotal.Add(e.Coins...)\n\t}\n\tnewTotal := sdk.NewCoins()\n\tfor _, e := range newEvents {\n\t\tnewTotal = newTotal.Add(e.Coins...)\n\t}\n\tif !oldTotal.IsEqual(newTotal) {\n\t\treturn nil, fmt.Errorf(\"applying vesting cliff changed total from %s to %s\", oldTotal, newTotal)\n\t}\n\treturn newEvents, nil\n}", "func (s *Store) Balance(ns walletdb.ReadBucket, minConf int32, syncHeight int32) (btcutil.Amount, error) {\n\tbal, err := fetchMinedBalance(ns)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\t// Subtract the balance for each credit that is spent by an unmined\n\t// transaction.\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\t\terr = readUnspentBlock(v, &block)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Subtract the output's amount if it's locked.\n\t\t_, _, isLocked := isLockedOutput(ns, op, s.clock.Now())\n\t\tif isLocked {\n\t\t\t_, v := existsCredit(ns, &op.Hash, op.Index, &block)\n\t\t\tamt, err := fetchRawCreditAmount(v)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tbal -= amt\n\n\t\t\t// To prevent decrementing the balance twice if the\n\t\t\t// output has an unconfirmed spend, return now.\n\t\t\treturn nil\n\t\t}\n\n\t\tif existsRawUnminedInput(ns, k) != nil {\n\t\t\t_, v := existsCredit(ns, &op.Hash, op.Index, &block)\n\t\t\tamt, err := fetchRawCreditAmount(v)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tbal -= amt\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tif _, ok := err.(Error); ok {\n\t\t\treturn 0, err\n\t\t}\n\t\tstr := \"failed iterating unspent outputs\"\n\t\treturn 0, storeError(ErrDatabase, str, err)\n\t}\n\n\t// Decrement the balance for any unspent credit with less than\n\t// minConf confirmations and any (unspent) immature coinbase credit.\n\tcoinbaseMaturity := int32(s.chainParams.CoinbaseMaturity)\n\tstopConf := minConf\n\tif coinbaseMaturity > stopConf {\n\t\tstopConf = coinbaseMaturity\n\t}\n\tlastHeight := syncHeight - stopConf\n\tblockIt := makeReadReverseBlockIterator(ns)\n\tfor blockIt.prev() {\n\t\tblock := &blockIt.elem\n\n\t\tif block.Height < lastHeight {\n\t\t\tbreak\n\t\t}\n\n\t\tfor i := range block.transactions {\n\t\t\ttxHash := &block.transactions[i]\n\t\t\trec, err := fetchTxRecord(ns, txHash, &block.Block)\n\t\t\tif err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t\tnumOuts := uint32(len(rec.MsgTx.TxOut))\n\t\t\tfor i := uint32(0); i < numOuts; i++ {\n\t\t\t\t// Avoid double decrementing the credit amount\n\t\t\t\t// if it was already removed for being spent by\n\t\t\t\t// an unmined tx or being locked.\n\t\t\t\top = wire.OutPoint{Hash: *txHash, Index: i}\n\t\t\t\t_, _, isLocked := isLockedOutput(\n\t\t\t\t\tns, op, s.clock.Now(),\n\t\t\t\t)\n\t\t\t\tif isLocked {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\topKey := canonicalOutPoint(txHash, i)\n\t\t\t\tif existsRawUnminedInput(ns, opKey) != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t_, v := existsCredit(ns, txHash, i, &block.Block)\n\t\t\t\tif v == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tamt, spent, err := fetchRawCreditAmountSpent(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn 0, err\n\t\t\t\t}\n\t\t\t\tif spent {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tconfs := syncHeight - block.Height + 1\n\t\t\t\tif confs < minConf || (blockchain.IsCoinBaseTx(&rec.MsgTx) &&\n\t\t\t\t\tconfs < coinbaseMaturity) {\n\t\t\t\t\tbal -= amt\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif blockIt.err != nil {\n\t\treturn 0, blockIt.err\n\t}\n\n\t// If unmined outputs are included, increment the balance for each\n\t// output that is unspent.\n\tif minConf == 0 {\n\t\terr = ns.NestedReadBucket(bucketUnminedCredits).ForEach(func(k, v []byte) error {\n\t\t\tif err := readCanonicalOutPoint(k, &op); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Skip adding the balance for this output if it's\n\t\t\t// locked.\n\t\t\t_, _, isLocked := isLockedOutput(ns, op, s.clock.Now())\n\t\t\tif isLocked {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tif existsRawUnminedInput(ns, k) != nil {\n\t\t\t\t// Output is spent by an unmined transaction.\n\t\t\t\t// Skip to next unmined credit.\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tamount, err := fetchRawUnminedCreditAmount(v)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tbal += amount\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\tif _, ok := err.(Error); ok {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t\tstr := \"failed to iterate over unmined credits bucket\"\n\t\t\treturn 0, storeError(ErrDatabase, str, err)\n\t\t}\n\t}\n\n\treturn bal, nil\n}", "func (va ClawbackVestingAccount) distributeReward(ctx sdk.Context, ak AccountKeeper, bondDenom string, reward sdk.Coins) {\n\tnow := ctx.BlockTime().Unix()\n\tt := va.StartTime\n\tfirstUnvestedPeriod := 0\n\tunvestedTokens := sdk.ZeroInt()\n\tfor i, period := range va.VestingPeriods {\n\t\tt += period.Length\n\t\tif t <= now {\n\t\t\tfirstUnvestedPeriod = i + 1\n\t\t\tcontinue\n\t\t}\n\t\tunvestedTokens = unvestedTokens.Add(period.Amount.AmountOf(bondDenom))\n\t}\n\n\trunningTotReward := sdk.NewCoins()\n\trunningTotStaking := sdk.ZeroInt()\n\tfor i := firstUnvestedPeriod; i < len(va.VestingPeriods); i++ {\n\t\tperiod := va.VestingPeriods[i]\n\t\trunningTotStaking = runningTotStaking.Add(period.Amount.AmountOf(bondDenom))\n\t\trunningTotRatio := runningTotStaking.ToDec().Quo(unvestedTokens.ToDec())\n\t\ttargetCoins := scaleCoins(reward, runningTotRatio)\n\t\tthisReward := targetCoins.Sub(runningTotReward)\n\t\trunningTotReward = targetCoins\n\t\tperiod.Amount = period.Amount.Add(thisReward...)\n\t\tva.VestingPeriods[i] = period\n\t}\n\n\tva.OriginalVesting = va.OriginalVesting.Add(reward...)\n\tak.SetAccount(ctx, &va)\n}", "func (_ChpRegistry *ChpRegistryCallerSession) CORESTAKINGAMOUNT() (*big.Int, error) {\n\treturn _ChpRegistry.Contract.CORESTAKINGAMOUNT(&_ChpRegistry.CallOpts)\n}", "func balance(w *model.Wal, n int64) int64 {\n\t// Invariant 1\n\t// (this loop will run at most once)\n\tfor w.Cur.Resv < n {\n\t\tm := w.Cur.Resv\n\t\tif needFree(w, m) != m {\n\t\t\tutils.Log.Warnln(\"need free\")\n\t\t\treturn 0\n\t\t}\n\n\t\tmoveResv(w.Tail, w.Cur, m)\n\t\tuseNext(w)\n\t}\n\treturn balanceRest(w, w.Cur, n)\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 (_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 DeductFees(blockTime time.Time, acc Account, fee StdFee) (Account, sdk.Result) {\n\tcoins := acc.GetCoins()\n\tfeeAmount := fee.Amount()\n\n\tif !feeAmount.IsValid() {\n\t\treturn nil, sdk.ErrInsufficientFee(fmt.Sprintf(\"invalid fee amount: %s\", feeAmount)).Result()\n\t}\n\n\t// get the resulting coins deducting the fees\n\tnewCoins, ok := coins.SafeSub(feeAmount)\n\tif ok {\n\t\treturn nil, sdk.ErrInsufficientFunds(\n\t\t\tfmt.Sprintf(\"insufficient funds to pay for fees; %s < %s\", coins, feeAmount),\n\t\t).Result()\n\t}\n\n\t// Validate the account has enough \"spendable\" coins as this will cover cases\n\t// such as vesting accounts.\n\tspendableCoins := acc.SpendableCoins(blockTime)\n\tif _, hasNeg := spendableCoins.SafeSub(feeAmount); hasNeg {\n\t\treturn nil, sdk.ErrInsufficientFunds(\n\t\t\tfmt.Sprintf(\"insufficient funds to pay for fees; %s < %s\", spendableCoins, feeAmount),\n\t\t).Result()\n\t}\n\n\tif err := acc.SetCoins(newCoins); err != nil {\n\t\treturn nil, sdk.ErrInternal(err.Error()).Result()\n\t}\n\n\treturn acc, sdk.Result{}\n}", "func (_ChpRegistry *ChpRegistrySession) CORESTAKINGAMOUNT() (*big.Int, error) {\n\treturn _ChpRegistry.Contract.CORESTAKINGAMOUNT(&_ChpRegistry.CallOpts)\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 sumCashloan(l *models.Loan, m *models.Message, db *gorm.DB, nc float32) error {\n\tvar uc models.UserCollection\n\tuc.CodUser = l.CodUser\n\terr := getLoan(l, db)\n\tif err != nil {\n\t\tm.Code = http.StatusBadRequest\n\t\tm.Message = \"no se encontro Prestamo\"\n\t\treturn err\n\t}\n\tl.Balance += nc\n\terr = updateLoan(l, db)\n\tif err != nil {\n\t\tm.Code = http.StatusBadGateway\n\t\tm.Message = \"no se pudo actualizar\"\n\t\treturn err\n\t}\n\tvar c models.Collection\n\tc.ID = l.CodCollection\n\terr = sumBalanceCollection(&c, m, db, nc)\n\tif err != nil {\n\t\treturn err\n\t}\n\tuc.CodCollection = l.CodCollection\n\terr = sumCashUserCollection(&uc, m, db, -nc)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (_Cakevault *CakevaultCallerSession) MAXWITHDRAWFEE() (*big.Int, error) {\n\treturn _Cakevault.Contract.MAXWITHDRAWFEE(&_Cakevault.CallOpts)\n}", "func (_GameJam *GameJamCaller) Balance(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _GameJam.contract.Call(opts, out, \"balance\")\n\treturn *ret0, err\n}", "func (_Cakevault *CakevaultSession) MAXWITHDRAWFEE() (*big.Int, error) {\n\treturn _Cakevault.Contract.MAXWITHDRAWFEE(&_Cakevault.CallOpts)\n}", "func (t *TaskChaincode) getBalance(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\t// 0\n\t// \"$account\"\n\tif len(args) != 1 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 1\")\n\t}\n\n\tfmt.Println(\"cacluate begins!\");\n\tif len(args[0]) <= 0 {\n\t\treturn shim.Error(\"1st argument must be a non-empty string\")\n\t}\n\n\taccount := args[0]\n\n\tqueryString := fmt.Sprintf(\"{\\\"selector\\\":{\\\"objectType\\\":\\\"PayTX\\\",\\\"payer\\\":\\\"%s\\\"}}\", account)\n\tqueryResults, err := getResultForQueryString(stub, queryString)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\n\tvar payerTXs []payTX\n\terr = json.Unmarshal(queryResults, &payerTXs)\n\tif err != nil {\n\t\tshim.Error(err.Error())\n\t}\n\n\t//fmt.Println(len(payTXs))\n\tvar i int\n\toutcomeVal := 0.0\n for i=0;i<len(payerTXs);i=i+1 {\n\t\tpayerTX := payerTXs[i]\n\t\toutcomeVal = outcomeVal + payerTX.Value\n\t}\n //fmt.Println(outcomeVal)\n\n\tqueryString = fmt.Sprintf(\"{\\\"selector\\\":{\\\"objectType\\\":\\\"PayTX\\\",\\\"payee\\\":\\\"%s\\\"}}\", account)\n\tqueryResults, err = getResultForQueryString(stub, queryString)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\n\tvar payeeTXs []payTX\n\terr = json.Unmarshal(queryResults, &payeeTXs)\n\tif err != nil {\n\t\tshim.Error(err.Error())\n\t}\n\n\tincomeVal := 0.0\n for i=0;i<len(payeeTXs);i=i+1 {\n\t\tpayeeTX := payeeTXs[i]\n\t\tincomeVal = incomeVal + payeeTX.Value\n\t}\n //fmt.Println(incomeVal)\n\n\tbalance := incomeVal - outcomeVal\n\t//fmt.Println(balance)\n balanceStr := strconv.FormatFloat(balance, 'f', 6, 64)\n\n return shim.Success([]byte(balanceStr))\n}", "func determineChurn(prevConsensus, newConsensus *tor.Consensus) Churn {\n\n\tgoneRelays := prevConsensus.Subtract(newConsensus)\n\tnewRelays := newConsensus.Subtract(prevConsensus)\n\n\tmax := math.Max(float64(prevConsensus.Length()), float64(newConsensus.Length()))\n\tnewChurn := (float64(newRelays.Length()) / max)\n\tgoneChurn := (float64(goneRelays.Length()) / max)\n\n\treturn Churn{newChurn, goneChurn}\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 (_DogsOfRome *DogsOfRomeCaller) Balance(opts *bind.CallOpts, arg0 common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _DogsOfRome.contract.Call(opts, out, \"balance\", arg0)\n\treturn *ret0, err\n}", "func (cva ContinuousVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn cva.OriginalVesting.Sub(cva.GetVestedCoins(blockTime))\n}", "func (bc *Blockchain) ProofOfWorkCalc(proof int, previous_proof int, Timestamp int64) string {\n // calculate the proof of work function\n var hash_PoW = sha256.New()\n result := (proof * proof) - (previous_proof * previous_proof) - int(Timestamp)\n hash_PoW.Write([]byte(strconv.Itoa(result)))\n hashed_PoW := hash_PoW.Sum(nil)\n result_hash := hex.EncodeToString(hashed_PoW)\n return result_hash\n}", "func (c *CheckpointAdvancer) CalculateGlobalCheckpoint(ctx context.Context) (uint64, error) {\n\tvar (\n\t\tcp = uint64(math.MaxInt64)\n\t\tthisRun []kv.KeyRange = c.taskRange\n\t\tnextRun []kv.KeyRange\n\t)\n\tdefer c.recordTimeCost(\"record all\")\n\tfor {\n\t\tcoll := NewClusterCollector(ctx, c.env)\n\t\tcoll.setOnSuccessHook(c.cache.InsertRange)\n\t\tfor _, u := range thisRun {\n\t\t\terr := c.GetCheckpointInRange(ctx, u.StartKey, u.EndKey, coll)\n\t\t\tif err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t}\n\t\tresult, err := coll.Finish(ctx)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tlog.Debug(\"full: a run finished\", zap.Any(\"checkpoint\", result))\n\n\t\tnextRun = append(nextRun, result.FailureSubRanges...)\n\t\tif cp > result.Checkpoint {\n\t\t\tcp = result.Checkpoint\n\t\t}\n\t\tif len(nextRun) == 0 {\n\t\t\treturn cp, nil\n\t\t}\n\t\tthisRun = nextRun\n\t\tnextRun = nil\n\t\tlog.Debug(\"backoffing with subranges\", zap.Int(\"subranges\", len(thisRun)))\n\t\ttime.Sleep(c.cfg.BackoffTime)\n\t}\n}", "func (_Cakevault *CakevaultCaller) MAXWITHDRAWFEE(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Cakevault.contract.Call(opts, &out, \"MAX_WITHDRAW_FEE\")\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 *Channel) Balance() *big.Int {\n\tx := new(big.Int)\n\tx.Sub(c.OurState.ContractBalance, c.OurState.TransferAmount())\n\tx.Add(x, c.PartnerState.TransferAmount())\n\treturn x\n}", "func (c *Channel) Balance() *big.Int {\n\tx := new(big.Int)\n\tx.Sub(c.OurState.ContractBalance, c.OurState.TransferAmount())\n\tx.Add(x, c.PartnerState.TransferAmount())\n\treturn x\n}", "func (c BaseController) Balance(store weave.KVStore, src weave.Address) (coin.Coins, error) {\n\tstate, err := c.bucket.Get(store, src)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"cannot get account state\")\n\t}\n\tif state == nil {\n\t\treturn nil, errors.Wrap(errors.ErrNotFound, \"no account\")\n\t}\n\treturn AsCoins(state), nil\n}", "func GenerateGetTotalCommitmentBalanceWithoutDelegatorsScript(env Environment) []byte {\n\tcode := assets.MustAssetString(getTotalCommitmentWithoutDelegatorsFilename)\n\n\treturn []byte(replaceAddresses(code, env))\n}", "func nextBalance(balance Balance, c *AccountConfig, elapsedSecs float32, runningJobs []int) Balance {\n\tvar runningJobsArray [NumPriorities]int\n\tcopy(runningJobsArray[:], runningJobs)\n\tfor priority := 0; priority < NumPriorities; priority++ {\n\t\tval := balance[priority]\n\t\tval -= elapsedSecs * float32(runningJobsArray[priority])\n\t\tchargeRate := c.ChargeRate[priority]\n\n\t\tmaxBalance := chargeRate * c.MaxChargeSeconds\n\t\t// Check for value overflow prior to recharging or capping, because\n\t\t// if the account value is already above cap we want to leave it there.\n\t\t// It likley got over cap due to preemption reimbursement.\n\t\tif val < maxBalance {\n\t\t\tval += elapsedSecs * chargeRate\n\t\t\tif val > maxBalance {\n\t\t\t\tval = maxBalance\n\t\t\t}\n\t\t}\n\t\tbalance[priority] = val\n\t}\n\n\treturn balance\n}", "func (sc Funcs) AccountNFTAmount(ctx wasmlib.ScViewClientContext) *AccountNFTAmountCall {\n\tf := &AccountNFTAmountCall{Func: wasmlib.NewScView(ctx, HScName, HViewAccountNFTAmount)}\n\tf.Params.Proxy = wasmlib.NewCallParamsProxy(f.Func)\n\twasmlib.NewCallResultsProxy(f.Func, &f.Results.Proxy)\n\treturn f\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 calcTotalBalance(chromoinfo []bybBalance) (totalBalace big.Int) {\n\n\tfor _, x := range chromoinfo {\n\t\ttotalBalace = Add(totalBalace, x.Value)\n\t}\n\treturn\n\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 (s *skill) currentCoolDown() float64 {\n\ts.m.Lock()\n\tdefer s.m.Unlock()\n\treturn s.internalCD\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 deleteActorWithBeneficiary(actorFunds big.Int, beneficiaryAddr address.Address, expectedCode exitcode.ExitCode) func(v *MessageVectorBuilder) {\n\treturn func(v *MessageVectorBuilder) {\n\t\tv.Messages.SetDefaults(GasLimit(1_000_000_000), GasPremium(1), GasFeeCap(200))\n\n\t\tsender := v.Actors.Account(address.SECP256K1, big.Add(big.NewInt(1_000_000_000_000_000), actorFunds))\n\n\t\tbeneficiaryAddr := beneficiaryAddr // capture\n\t\tif beneficiaryAddr == address.Undef {\n\t\t\tbeneficiaryAddr = v.Actors.Account(address.SECP256K1, big.Zero()).ID\n\t\t}\n\n\t\tv.CommitPreconditions()\n\n\t\tv.Assert.ActorExists(chaos.Address)\n\t\tv.Assert.BalanceEq(chaos.Address, big.Zero())\n\n\t\t// transfer required funds to the actor that will be deleted\n\t\tm := v.Messages.Sugar().Transfer(sender.ID, chaos.Address, Value(actorFunds), Nonce(0))\n\t\tv.Messages.ApplyOne(m)\n\t\tv.Assert.EveryMessageResultSatisfies(ExitCode(exitcode.Ok))\n\n\t\t// if this is will succeed, record the current balance so we can check funds\n\t\t// were transferred to the beneficiary\n\t\tvar bal big.Int\n\t\tif expectedCode == exitcode.Ok {\n\t\t\tbal = v.StateTracker.Balance(beneficiaryAddr)\n\t\t}\n\n\t\tv.Messages.Raw(\n\t\t\tsender.ID,\n\t\t\tchaos.Address,\n\t\t\tchaos.MethodDeleteActor,\n\t\t\tMustSerialize(&beneficiaryAddr),\n\t\t\tValue(big.Zero()),\n\t\t\tNonce(1),\n\t\t)\n\t\tv.CommitApplies()\n\n\t\tv.Assert.LastMessageResultSatisfies(ExitCode(expectedCode))\n\n\t\t// check beneficiary received funds if it succeeded\n\t\tif expectedCode == exitcode.Ok && beneficiaryAddr != chaos.Address {\n\t\t\tv.Assert.ActorMissing(chaos.Address)\n\t\t\tv.Assert.BalanceEq(beneficiaryAddr, big.Add(bal, actorFunds))\n\t\t}\n\t}\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 (sc Funcs) Balance(ctx wasmlib.ScViewClientContext) *BalanceCall {\n\tf := &BalanceCall{Func: wasmlib.NewScView(ctx, HScName, HViewBalance)}\n\tf.Params.Proxy = wasmlib.NewCallParamsProxy(f.Func)\n\twasmlib.NewCallResultsProxy(f.Func, &f.Results.Proxy)\n\treturn f\n}", "func totalFees(block *model.Block, receipts []*model.Receipt) *big.Float {\n\tfeesWei := new(big.Int)\n\tfor i, tx := range block.Transactions() {\n\t\tminerFee, _ := tx.EffectiveGasTip(block.BaseFee())\n\t\tfeesWei.Add(feesWei, new(big.Int).Mul(new(big.Int).SetUint64(receipts[i].GasUsed), minerFee))\n\t}\n\treturn new(big.Float).Quo(new(big.Float).SetInt(feesWei), new(big.Float).SetInt(big.NewInt(config.Ether)))\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 (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 (_GameJam *GameJamCallerSession) Balance() (*big.Int, error) {\n\treturn _GameJam.Contract.Balance(&_GameJam.CallOpts)\n}", "func (w *worker) externSyncAccountBalanceToHost() {\n\t// Spin/block until the worker has no jobs in motion. This should only be\n\t// called from the primary loop of the worker, meaning that no new jobs will\n\t// be launched while we spin.\n\tisIdle := func() bool {\n\t\tsls := w.staticLoopState\n\t\ta := atomic.LoadUint64(&sls.atomicSerialJobRunning) == 0\n\t\tb := atomic.LoadUint64(&sls.atomicAsyncJobsRunning) == 0\n\t\treturn a && b\n\t}\n\tstart := time.Now()\n\tfor !isIdle() {\n\t\tif time.Since(start) > accountIdleMaxWait {\n\t\t\t// The worker failed to go idle for too long. Print the loop state,\n\t\t\t// so we know what kind of task is keeping it busy.\n\t\t\tw.renter.log.Printf(\"Worker static loop state: %+v\\n\\n\", w.staticLoopState)\n\t\t\t// Get the stack traces of all running goroutines.\n\t\t\tbuf := make([]byte, modules.StackSize) // 64MB\n\t\t\tn := runtime.Stack(buf, true)\n\t\t\tw.renter.log.Println(string(buf[:n]))\n\t\t\tw.renter.log.Critical(fmt.Sprintf(\"worker has taken more than %v minutes to go idle\", accountIdleMaxWait.Minutes()))\n\t\t\treturn\n\t\t}\n\t\tawake := w.renter.tg.Sleep(accountIdleCheckFrequency)\n\t\tif !awake {\n\t\t\treturn\n\t\t}\n\t}\n\t// Do a check to ensure that the worker is still idle after the function is\n\t// complete. This should help to catch any situation where the worker is\n\t// spinning up new jobs, even though it is not supposed to be spinning up\n\t// new jobs while it is performing the sync operation.\n\tdefer func() {\n\t\tif !isIdle() {\n\t\t\tw.renter.log.Critical(\"worker appears to be spinning up new jobs during managedSyncAccountBalanceToHost\")\n\t\t}\n\t}()\n\n\t// Sanity check the account's deltas are zero, indicating there are no\n\t// in-progress jobs\n\tw.staticAccount.mu.Lock()\n\tdeltasAreZero := w.staticAccount.pendingDeposits.IsZero() && w.staticAccount.pendingWithdrawals.IsZero()\n\tw.staticAccount.mu.Unlock()\n\tif !deltasAreZero {\n\t\tbuild.Critical(\"managedSyncAccountBalanceToHost is called on a worker with an account that has non-zero deltas, indicating in-progress jobs\")\n\t}\n\n\t// Track the outcome of the account sync - this ensures a proper working of\n\t// the maintenance cooldown mechanism.\n\tbalance, err := w.staticHostAccountBalance()\n\tw.managedTrackAccountSyncErr(err)\n\tif err != nil {\n\t\tw.renter.log.Debugf(\"ERROR: failed to check account balance on host %v failed, err: %v\\n\", w.staticHostPubKeyStr, err)\n\t\treturn\n\t}\n\n\t// If our account balance is lower than the balance indicated by the host,\n\t// we want to sync our balance by resetting it.\n\tif w.staticAccount.managedAvailableBalance().Cmp(balance) < 0 {\n\t\tw.staticAccount.managedResetBalance(balance)\n\t}\n\n\t// Determine how long to wait before attempting to sync again, and then\n\t// update the syncAt time. There is significant randomness in the waiting\n\t// because syncing with the host requires freezing up the worker. We do not\n\t// want to freeze up a large number of workers at once, nor do we want to\n\t// freeze them frequently.\n\twaitTime := time.Duration(fastrand.Intn(accountSyncRandWaitMilliseconds)) * time.Millisecond\n\twaitTime += accountSyncMinWaitTime\n\tw.staticAccount.callSetSyncAt(time.Now().Add(waitTime))\n\n\t// TODO perform a thorough balance comparison to decide whether the drift in\n\t// the account balance is warranted. If not the host needs to be penalized\n\t// accordingly. Perform this check at startup and periodically.\n}", "func (_Cakevault *CakevaultSession) CalculateHarvestCakeRewards() (*big.Int, error) {\n\treturn _Cakevault.Contract.CalculateHarvestCakeRewards(&_Cakevault.CallOpts)\n}", "func testWithdrawZeroBalance(t *testing.T, n int) {\n\trng := pkgtest.Prng(t)\n\ts := test.NewSetup(t, rng, n)\n\t// create valid state and params\n\tparams, state := channeltest.NewRandomParamsAndState(rng, channeltest.WithParts(s.Parts...), channeltest.WithAssets((*ethchannel.Asset)(&s.Asset)), channeltest.WithIsFinal(true))\n\tagreement := state.Balances.Clone()\n\n\tfor i := range params.Parts {\n\t\tif i%2 == 0 {\n\t\t\tstate.Balances[0][i].SetInt64(0)\n\t\t\tagreement[0][i].SetInt64(0)\n\t\t} // is != 0 otherwise\n\t\tt.Logf(\"Part: %d ShouldFund: %t Bal: %v\", i, i%2 == 1, state.Balances[0][i])\n\t}\n\n\t// fund\n\tct := pkgtest.NewConcurrent(t)\n\tfor i, funder := range s.Funders {\n\t\ti, funder := i, funder\n\t\tgo ct.StageN(\"funding loop\", n, func(rt pkgtest.ConcT) {\n\t\t\treq := channel.NewFundingReq(params, state, channel.Index(i), agreement)\n\t\t\trequire.NoError(rt, funder.Fund(context.Background(), *req), \"funding should succeed\")\n\t\t})\n\t}\n\tct.Wait(\"funding loop\")\n\n\t// register\n\treq := channel.AdjudicatorReq{\n\t\tParams: params,\n\t\tAcc: s.Accs[0],\n\t\tTx: testSignState(t, s.Accs, params, state),\n\t\tIdx: 0,\n\t}\n\trequire.NoError(t, s.Adjs[0].Register(context.Background(), req))\n\t// we don't need to wait for a timeout since we registered a final state\n\n\t// withdraw\n\tfor i, _adj := range s.Adjs {\n\t\tadj := _adj\n\t\treq.Acc = s.Accs[i]\n\t\treq.Idx = channel.Index(i)\n\t\t// check that the nonce stays the same for zero balance withdrawals\n\t\tdiff, err := test.NonceDiff(s.Accs[i].Address(), adj, func() error {\n\t\t\treturn adj.Withdraw(context.Background(), req, nil)\n\t\t})\n\t\trequire.NoError(t, err)\n\t\tif i%2 == 0 {\n\t\t\tassert.Zero(t, diff, \"Nonce should stay the same\")\n\t\t} else {\n\t\t\tassert.Equal(t, 1, diff, \"Nonce should increase by 1\")\n\t\t}\n\t}\n\tassertHoldingsZero(context.Background(), t, s.CB, params, state.Assets)\n}", "func (dva DelayedVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn dva.OriginalVesting.Sub(dva.GetVestedCoins(blockTime))\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 (w *Wallet) VacuumDb(startKey string, maxTime time.Duration) (*btcjson.VacuumDbRes, er.R) {\n\tdeadline := time.Now().Add(maxTime)\n\tstats := btcjson.VacuumDbRes{}\n\tif sk, errr := hex.DecodeString(startKey); errr != nil {\n\t\treturn nil, er.E(errr)\n\t} else if chainClient, err := w.requireChainClient(); err != nil {\n\t\treturn nil, err\n\t} else if bs, err := chainClient.BlockStamp(); err != nil {\n\t\treturn nil, err\n\t} else if err := walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) er.R {\n\t\ttxNs := tx.ReadWriteBucket(wtxmgrNamespaceKey)\n\t\tvar badOutputs []wtxmgr.Credit\n\t\ti := 0\n\t\tif err := w.TxStore.ForEachUnspentOutput(txNs, sk, func(k []byte, op *wtxmgr.Credit) er.R {\n\t\t\tif maxTime > 0 && time.Now().After(deadline) {\n\t\t\t\tstats.EndKey = hex.EncodeToString(k)\n\t\t\t\treturn er.LoopBreak\n\t\t\t}\n\t\t\ti++\n\t\t\tif txrules.IsBurned(op, w.chainParams, bs.Height) {\n\t\t\t\tlog.Debugf(\"Removing tx [%s] which has burned\",\n\t\t\t\t\top.OutPoint.Hash.String())\n\t\t\t\tbadOutputs = append(badOutputs, *op)\n\t\t\t\tstats.Burned++\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif op.Height < 0 {\n\t\t\t} else if _, err := chainClient.GetBlockHeader(&op.Block.Hash); err != nil {\n\t\t\t\tlog.Debugf(\"Removing tx [%s] because it references orphan block [%s]\",\n\t\t\t\t\top.OutPoint.Hash.String(), op.Block.Hash)\n\t\t\t\tbadOutputs = append(badOutputs, *op)\n\t\t\t\tstats.Orphaned++\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn nil\n\t\t}); err != nil && !er.IsLoopBreak(err) {\n\t\t\treturn err\n\t\t}\n\t\tstats.VisitedUtxos = i\n\t\tfor _, op := range badOutputs {\n\t\t\tif err := wtxmgr.RollbackTransaction(txNs, &op.OutPoint.Hash, &op.Block); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}); err != nil {\n\t\treturn &stats, err\n\t}\n\treturn &stats, nil\n}", "func (u *User) WithdrawCash(amount int) int {\n\tif amount <= 0 {\n\t\treturn u.cash\n\t}\n\n\tif amount > u.cash {\n\t\treturn u.cash\n\t}\n\n\tu.cash -= amount\n\treturn u.cash\n}", "func calculateTicketValue(\n\tbeaconOutput []byte,\n\tstakerValue []byte,\n\tvirtualStakerIndex *big.Int,\n) ([8]byte, error) {\n\tvar combinedValue []byte\n\tvar ticketValue [8]byte\n\n\tbeaconOutputPadded, err := byteutils.LeftPadTo32Bytes(beaconOutput)\n\tif err != nil {\n\t\treturn ticketValue, fmt.Errorf(\"cannot pad a becon output, [%v]\", err)\n\t}\n\n\tstakerValuePadded, err := byteutils.LeftPadTo32Bytes(stakerValue)\n\tif err != nil {\n\t\treturn ticketValue, fmt.Errorf(\"cannot pad a staker value, [%v]\", err)\n\t}\n\n\tvirtualStakerIndexPadded, err := byteutils.LeftPadTo32Bytes(virtualStakerIndex.Bytes())\n\tif err != nil {\n\t\treturn ticketValue, fmt.Errorf(\"cannot pad a virtual staker index, [%v]\", err)\n\t}\n\n\tcombinedValue = append(combinedValue, beaconOutputPadded...)\n\tcombinedValue = append(combinedValue, stakerValuePadded...)\n\tcombinedValue = append(combinedValue, virtualStakerIndexPadded...)\n\n\tcopy(ticketValue[:], crypto.Keccak256(combinedValue[:])[:8])\n\n\treturn ticketValue, nil\n}", "func NewClawbackAction(requestor, dest sdk.AccAddress, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) exported.ClawbackAction {\n\treturn clawbackAction{\n\t\trequestor: requestor,\n\t\tdest: dest,\n\t\tak: ak,\n\t\tbk: bk,\n\t\tsk: sk,\n\t}\n}", "func (s *State) applyContractMaintenance(td *TransactionDiff) (diffs []OutputDiff) {\n\t// Scan all open contracts and perform any required maintenance on each.\n\tvar contractsToDelete []ContractID\n\tfor _, openContract := range s.openContracts {\n\t\t// Check if the window index is changing.\n\t\tcontract := openContract.FileContract\n\t\tcontractProgress := s.height() - contract.Start\n\t\tif s.height() > contract.Start && contractProgress%contract.ChallengeWindow == 0 {\n\t\t\t// If the proof was missed for this window, add an output.\n\t\t\tcd := ContractDiff{\n\t\t\t\tContract: openContract.FileContract,\n\t\t\t\tContractID: openContract.ContractID,\n\t\t\t\tNew: false,\n\t\t\t\tTerminated: false,\n\t\t\t\tPreviousOpenContract: *openContract,\n\t\t\t}\n\t\t\tif openContract.WindowSatisfied == false {\n\t\t\t\tdiff := s.applyMissedProof(openContract)\n\t\t\t\tdiffs = append(diffs, diff)\n\t\t\t} else {\n\t\t\t\ts.currentBlockNode().SuccessfulWindows = append(s.currentBlockNode().SuccessfulWindows, openContract.ContractID)\n\t\t\t}\n\t\t\topenContract.WindowSatisfied = false\n\t\t\tcd.NewOpenContract = *openContract\n\t\t\ttd.ContractDiffs = append(td.ContractDiffs, cd)\n\t\t}\n\n\t\t// Check for a terminated contract.\n\t\tif openContract.FundsRemaining == 0 || contract.End == s.height() || contract.Tolerance == openContract.Failures {\n\t\t\tif openContract.FundsRemaining != 0 {\n\t\t\t\t// Create a new output that terminates the contract.\n\t\t\t\toutput := Output{\n\t\t\t\t\tValue: openContract.FundsRemaining,\n\t\t\t\t}\n\n\t\t\t\t// Get the output address.\n\t\t\t\tcontractSuccess := openContract.Failures != openContract.FileContract.Tolerance\n\t\t\t\tif contractSuccess {\n\t\t\t\t\toutput.SpendHash = contract.ValidProofAddress\n\t\t\t\t} else {\n\t\t\t\t\toutput.SpendHash = contract.MissedProofAddress\n\t\t\t\t}\n\n\t\t\t\t// Create the output.\n\t\t\t\toutputID := ContractTerminationOutputID(openContract.ContractID, contractSuccess)\n\t\t\t\ts.unspentOutputs[outputID] = output\n\t\t\t\tdiff := OutputDiff{New: true, ID: outputID, Output: output}\n\t\t\t\tdiffs = append(diffs, diff)\n\t\t\t}\n\n\t\t\t// Add the contract to contract terminations.\n\t\t\ts.currentBlockNode().ContractTerminations = append(s.currentBlockNode().ContractTerminations, openContract)\n\n\t\t\t// Mark contract for deletion (can't delete from a map while\n\t\t\t// iterating through it - results in undefined behavior of the\n\t\t\t// iterator.\n\t\t\tcontractsToDelete = append(contractsToDelete, openContract.ContractID)\n\t\t}\n\t}\n\n\t// Delete all of the contracts that terminated.\n\tfor _, contractID := range contractsToDelete {\n\t\tdelete(s.openContracts, contractID)\n\t}\n\treturn\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 Balance() int {\n\treturn <-balances\n}", "func (vva ValidatorVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.OriginalVesting.Sub(vva.GetVestedCoins(blockTime))\n}", "func (_Cakevault *CakevaultCaller) CalculateHarvestCakeRewards(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Cakevault.contract.Call(opts, &out, \"calculateHarvestCakeRewards\")\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 *breachArbiter) contractObserver(activeChannels []*lnwallet.LightningChannel) {\n\tdefer b.wg.Done()\n\n\t// For each active channel found within the database, we launch a\n\t// detected breachObserver goroutine for that channel and also track\n\t// the new goroutine within the breachObservers map so we can cancel it\n\t// later if necessary.\n\tfor _, channel := range activeChannels {\n\t\tsettleSignal := make(chan struct{})\n\t\tchanPoint := channel.ChannelPoint()\n\t\tb.breachObservers[*chanPoint] = settleSignal\n\n\t\tb.wg.Add(1)\n\t\tgo b.breachObserver(channel, settleSignal)\n\t}\n\n\t// TODO(roasbeef): need to ensure currentHeight passed in doesn't\n\t// result in lost notification\n\nout:\n\tfor {\n\t\tselect {\n\t\tcase breachInfo := <-b.breachedContracts:\n\t\t\t_, currentHeight, err := b.chainIO.GetBestBlock()\n\t\t\tif err != nil {\n\t\t\t\tbrarLog.Errorf(\"unable to get best height: %v\", err)\n\t\t\t}\n\n\t\t\t// A new channel contract has just been breached! We\n\t\t\t// first register for a notification to be dispatched\n\t\t\t// once the breach transaction (the revoked commitment\n\t\t\t// transaction) has been confirmed in the chain to\n\t\t\t// ensure we're not dealing with a moving target.\n\t\t\tbreachTXID := &breachInfo.commitHash\n\t\t\tconfChan, err := b.notifier.RegisterConfirmationsNtfn(\n\t\t\t\tbreachTXID, 1, uint32(currentHeight),\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\tbrarLog.Errorf(\"unable to register for conf for txid: %v\",\n\t\t\t\t\tbreachTXID)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tbrarLog.Warnf(\"A channel has been breached with tx: %v. \"+\n\t\t\t\t\"Waiting for confirmation, then justice will be served!\",\n\t\t\t\tbreachTXID)\n\n\t\t\t// With the notification registered, we launch a new\n\t\t\t// goroutine which will finalize the channel\n\t\t\t// retribution after the breach transaction has been\n\t\t\t// confirmed.\n\t\t\tb.wg.Add(1)\n\t\t\tgo b.exactRetribution(confChan, breachInfo)\n\n\t\t\tdelete(b.breachObservers, breachInfo.chanPoint)\n\t\tcase contract := <-b.newContracts:\n\t\t\t// A new channel has just been opened within the\n\t\t\t// daemon, so we launch a new breachObserver to handle\n\t\t\t// the detection of attempted contract breaches.\n\t\t\tsettleSignal := make(chan struct{})\n\t\t\tchanPoint := contract.ChannelPoint()\n\n\t\t\t// If the contract is already being watched, then an\n\t\t\t// additional send indicates we have a stale version of\n\t\t\t// the contract. So we'll cancel active watcher\n\t\t\t// goroutine to create a new instance with the latest\n\t\t\t// contract reference.\n\t\t\tif oldSignal, ok := b.breachObservers[*chanPoint]; ok {\n\t\t\t\tbrarLog.Infof(\"ChannelPoint(%v) is now live, \"+\n\t\t\t\t\t\"abandoning state contract for live \"+\n\t\t\t\t\t\"version\", chanPoint)\n\t\t\t\tclose(oldSignal)\n\t\t\t}\n\n\t\t\tb.breachObservers[*chanPoint] = settleSignal\n\n\t\t\tbrarLog.Debugf(\"New contract detected, launching \" +\n\t\t\t\t\"breachObserver\")\n\n\t\t\tb.wg.Add(1)\n\t\t\tgo b.breachObserver(contract, settleSignal)\n\n\t\t\t// TODO(roasbeef): add doneChan to signal to peer continue\n\t\t\t// * peer send over to us on loadActiveChanenls, sync\n\t\t\t// until we're aware so no state transitions\n\t\tcase chanPoint := <-b.settledContracts:\n\t\t\t// A new channel has been closed either unilaterally or\n\t\t\t// cooperatively, as a result we no longer need a\n\t\t\t// breachObserver detected to the channel.\n\t\t\tkillSignal, ok := b.breachObservers[*chanPoint]\n\t\t\tif !ok {\n\t\t\t\tbrarLog.Errorf(\"Unable to find contract: %v\",\n\t\t\t\t\tchanPoint)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tbrarLog.Debugf(\"ChannelPoint(%v) has been settled, \"+\n\t\t\t\t\"cancelling breachObserver\", chanPoint)\n\n\t\t\t// If we had a breachObserver active, then we signal it\n\t\t\t// for exit and also delete its state from our tracking\n\t\t\t// map.\n\t\t\tclose(killSignal)\n\t\t\tdelete(b.breachObservers, *chanPoint)\n\t\tcase <-b.quit:\n\t\t\tbreak out\n\t\t}\n\t}\n\n\treturn\n}", "func (_Cakevault *CakevaultCallerSession) WithdrawFee() (*big.Int, error) {\n\treturn _Cakevault.Contract.WithdrawFee(&_Cakevault.CallOpts)\n}", "func (s *State) returnDeposit(tx *types.Transaction, height uint32) {\n\tvar inputValue common.Fixed64\n\tfor _, input := range tx.Inputs {\n\t\tinputValue += s.DepositOutputs[input.ReferKey()]\n\t}\n\n\treturnAction := func(producer *Producer) {\n\t\ts.history.Append(height, func() {\n\t\t\tif height >= s.chainParams.CRVotingStartHeight {\n\t\t\t\tproducer.depositAmount -= inputValue\n\t\t\t}\n\t\t\tproducer.state = Returned\n\t\t}, func() {\n\t\t\tif height >= s.chainParams.CRVotingStartHeight {\n\t\t\t\tproducer.depositAmount += inputValue\n\t\t\t}\n\t\t\tproducer.state = Canceled\n\t\t})\n\t}\n\n\tfor _, program := range tx.Programs {\n\t\tpk := program.Code[1 : len(program.Code)-1]\n\t\tif producer := s.getProducer(pk); producer != nil && producer.state == Canceled {\n\t\t\treturnAction(producer)\n\t\t}\n\t}\n}", "func (f *FinalizedChain) ColdEnd() Step {\n\tf.RLock()\n\tdefer f.RUnlock()\n\treturn f.end()\n}", "func (a *account) maxExpectedBalance() types.Currency {\n\t// NOTE: negativeBalance will never be larger than the sum of the pending\n\t// deposits. If that does happen, this will build.Critical which indicates\n\t// that something is incorrect within the worker's internal accounting.\n\treturn a.balance.Add(a.pendingDeposits).Sub(a.negativeBalance)\n}", "func (c *client) updateGiftConfidence(island shared.ClientID) int {\n\tturn := c.gameState().Turn\n\tpastConfidence := c.confidence(\"Gifts\", island)\n\n\tvar bufferLen = 0\n\tif turn < 10 {\n\t\tbufferLen = int(turn)\n\t} else {\n\t\tbufferLen = 10\n\t}\n\n\trunMeanTheyReq := 0.0\n\trunMeanTheyDon := 0.0\n\trunMeanWeReq := 0.0\n\trunMeanWeDon := 0.0\n\n\tourReqMap := c.giftHist[island].OurRequest\n\ttheirReqMap := c.giftHist[island].IslandRequest\n\n\tourKeys := make([]int, 0)\n\tfor k, _ := range ourReqMap {\n\t\tourKeys = append(ourKeys, int(k))\n\t}\n\n\ttheirKeys := make([]int, 0)\n\tfor k, _ := range theirReqMap {\n\t\ttheirKeys = append(theirKeys, int(k))\n\t}\n\n\t// Sort the keys in decreasing order\n\tsort.Ints(ourKeys)\n\tsort.Ints(theirKeys)\n\n\t// Take running average of the interactions\n\t// The individual turn values will be scaled wrt to the \"distance\" from the current turn\n\t// ie transactions further in the past are valued less\n\tif MinInt(len(ourKeys), len(theirKeys)) == 0 {\n\t\treturn pastConfidence\n\t}\n\tc.Logf(\"Bufferlen %v\", bufferLen)\n\tfor i := 0; i < MinInt(bufferLen, len(ourKeys)); i++ {\n\t\t// Get the transaction distance to the previous transaction\n\t\tourTransDist := turn - uint(ourKeys[i])\n\t\t// Update the respective running mean factoring in the transactionDistance (inv proportioanl to transactionDistance so farther transactions are weighted less)\n\t\trunMeanTheyDon = runMeanTheyDon + (float64(ourReqMap[uint(ourKeys[i])].gifted)/float64(ourTransDist)-float64(runMeanTheyDon))/float64(i+1)\n\t\trunMeanWeReq = runMeanWeReq + (float64(ourReqMap[uint(ourKeys[i])].requested)/float64(ourTransDist)-float64(runMeanWeReq))/float64(i+1)\n\t}\n\tfor i := 0; i < MinInt(bufferLen, len(theirKeys)); i++ {\n\t\t// Get the transaction distance to the previous transaction\n\t\ttheirTransDist := turn - uint(theirKeys[i])\n\t\t// Update the respective running mean factoring in the transactionDistance (inv proportioanl to transactionDistance so farther transactions are weighted less)\n\t\trunMeanTheyReq = runMeanTheyReq + (float64(theirReqMap[uint(theirKeys[i])].requested)/float64(theirTransDist)-float64(runMeanTheyReq))/float64(i+1)\n\t\trunMeanWeDon = runMeanWeDon + (float64(theirReqMap[uint(theirKeys[i])].gifted))/float64(theirTransDist) - float64(runMeanWeDon)/float64(i+1)\n\t}\n\n\t// TODO: is there a potential divide by 0 here?\n\tusRatio := runMeanTheyDon / runMeanWeReq // between 0 and 1\n\tthemRatio := runMeanWeDon / runMeanTheyReq // between 0 and 1\n\n\tdiff := usRatio - themRatio // between -1 and 1\n\t// confidence increases if usRatio >= themRatio\n\t// confidence decreases if not\n\n\t// e.g. 1 pastConfidnece = 50%\n\t// diff = 100% in our favour 1.0\n\t// inc pastConfidence = (50 + 100)/2 = 75\n\n\t// e.g. 2 pastConfidence = 90%\n\t// diff = 70% in our favour\n\t// inc pastConfidence = (90 + 70)/2 = 80\n\n\t// e.g. 3 pastConfidence = 80%\n\t// diff = 30% against us\n\t// inc pastConfidence = (80 - 30)/2 = 25\n\n\t// e.g. 4 pastConfidence = 100%\n\t// diff = 100% against us\n\t// inc pastConfidence = (100 - 100)/2 = 0\n\n\t// e.g. 5 pastConfidence = 0%\n\t// diff = 100% in our favour\n\t// inc pastConfidence = (0 + 100)/2 = 50\n\n\t// TODO: improve how ratios are used to improve pastConfidence\n\t// pastConfidence = (pastConfidence + sensitivity*diff*100) / 2\n\tpastConfidence = int((pastConfidence + int(diff*100)) / 2)\n\n\treturn pastConfidence\n}", "func (_Cakevault *CakevaultCallerSession) CalculateHarvestCakeRewards() (*big.Int, error) {\n\treturn _Cakevault.Contract.CalculateHarvestCakeRewards(&_Cakevault.CallOpts)\n}", "func (_Cakevault *CakevaultSession) WithdrawFee() (*big.Int, error) {\n\treturn _Cakevault.Contract.WithdrawFee(&_Cakevault.CallOpts)\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 (_Cakevault *CakevaultCaller) WithdrawFee(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Cakevault.contract.Call(opts, &out, \"withdrawFee\")\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 TestFundsStateChangeRollback(t *testing.T) {\n\tcleanAndPrepare()\n\n\trandVar := rand.New(rand.NewSource(time.Now().Unix()))\n\n\taccAHash := protocol.SerializeHashContent(accA.Address)\n\taccBHash := protocol.SerializeHashContent(accB.Address)\n\tminerAccHash := protocol.SerializeHashContent(validatorAcc.Address)\n\n\tvar testSize uint32\n\ttestSize = 1000\n\n\tb := newBlock([32]byte{}, [crypto.COMM_PROOF_LENGTH]byte{}, 1)\n\tvar funds []*protocol.FundsTx\n\n\tvar feeA, feeB uint64\n\n\t//State snapshot\n\trollBackA := accA.Balance\n\trollBackB := accB.Balance\n\n\t//Record transaction amounts in this variables\n\tbalanceA := accA.Balance\n\tbalanceB := accB.Balance\n\n\tloopMax := int(randVar.Uint32()%testSize + 1)\n\tfor i := 0; i < loopMax+1; i++ {\n\t\tftx, _ := protocol.ConstrFundsTx(0x01, randVar.Uint64()%1000000+1, randVar.Uint64()%100+1, uint32(i), accAHash, accBHash, PrivKeyAccA, PrivKeyMultiSig, nil)\n\t\tif addTx(b, ftx) == nil {\n\t\t\tfunds = append(funds, ftx)\n\t\t\tbalanceA -= ftx.Amount\n\t\t\tfeeA += ftx.Fee\n\n\t\t\tbalanceB += ftx.Amount\n\t\t} else {\n\t\t\tt.Errorf(\"Block rejected a valid transaction: %v\\n\", ftx)\n\t\t}\n\n\t\tftx2, _ := protocol.ConstrFundsTx(0x01, randVar.Uint64()%1000+1, randVar.Uint64()%100+1, uint32(i), accBHash, accAHash, PrivKeyAccB, PrivKeyMultiSig, nil)\n\t\tif addTx(b, ftx2) == nil {\n\t\t\tfunds = append(funds, ftx2)\n\t\t\tbalanceB -= ftx2.Amount\n\t\t\tfeeB += ftx2.Fee\n\n\t\t\tbalanceA += ftx2.Amount\n\t\t} else {\n\t\t\tt.Errorf(\"Block rejected a valid transaction: %v\\n\", ftx2)\n\t\t}\n\t}\n\tfundsStateChange(funds)\n\tif accA.Balance != balanceA || accB.Balance != balanceB {\n\t\tt.Error(\"State update failed!\")\n\t}\n\tfundsStateChangeRollback(funds)\n\tif accA.Balance != rollBackA || accB.Balance != rollBackB {\n\t\tt.Error(\"Rollback failed!\")\n\t}\n\n\t//collectTxFees is checked below in its own test (to additionally cover overflow scenario)\n\tbalBeforeRew := validatorAcc.Balance\n\treward := 5\n\tcollectBlockReward(uint64(reward), minerAccHash)\n\tif validatorAcc.Balance != balBeforeRew+uint64(reward) {\n\t\tt.Error(\"Block reward collection failed!\")\n\t}\n\tcollectBlockRewardRollback(uint64(reward), minerAccHash)\n\tif validatorAcc.Balance != balBeforeRew {\n\t\tt.Error(\"Block reward collection rollback failed!\")\n\t}\n}", "func (w *Wallet) CalculateBalance(confirms int32) (btcutil.Amount, er.R) {\n\tvar balance btcutil.Amount\n\terr := walletdb.View(w.db, func(tx walletdb.ReadTx) er.R {\n\t\ttxmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)\n\t\tvar err er.R\n\t\tblk := w.Manager.SyncedTo()\n\t\tbalance, err = w.TxStore.Balance(txmgrNs, confirms, blk.Height)\n\t\treturn err\n\t})\n\treturn balance, err\n}", "func (e *engineImpl) Finalize(\n\tchain engine.ChainReader, header *block.Header,\n\tstate *state.DB, txs []*types.Transaction,\n\treceipts []*types.Receipt, outcxs []*types.CXReceipt,\n\tincxs []*types.CXReceiptsProof, stks []*staking.StakingTransaction,\n) (*types.Block, *big.Int, error) {\n\n\t// Accumulate any block and uncle rewards and commit the final state root\n\t// Header seems complete, assemble into a block and return\n\tpayout, err := AccumulateRewards(\n\t\tchain, state, header, e.Rewarder(), e.Slasher(), e.Beaconchain(),\n\t)\n\tif err != nil {\n\t\treturn nil, nil, ctxerror.New(\"cannot pay block reward\").WithCause(err)\n\t}\n\n\t// Withdraw unlocked tokens to the delegators' accounts\n\t// Only do such at the last block of an epoch\n\tif header.ShardID() == shard.BeaconChainShardID && len(header.ShardState()) > 0 {\n\t\tvalidators, err := chain.ReadValidatorList()\n\t\tif err != nil {\n\t\t\treturn nil, nil, ctxerror.New(\"[Finalize] failed to read active validators\").WithCause(err)\n\t\t}\n\t\t// Payout undelegated/unlocked tokens\n\t\tfor _, validator := range validators {\n\t\t\twrapper := state.GetStakingInfo(validator)\n\t\t\tif wrapper != nil {\n\t\t\t\tfor i := range wrapper.Delegations {\n\t\t\t\t\tdelegation := &wrapper.Delegations[i]\n\t\t\t\t\ttotalWithdraw := delegation.RemoveUnlockedUndelegations(header.Epoch(), wrapper.LastEpochInCommittee)\n\t\t\t\t\tstate.AddBalance(delegation.DelegatorAddress, totalWithdraw)\n\t\t\t\t}\n\t\t\t\tif err := state.UpdateStakingInfo(validator, wrapper); err != nil {\n\t\t\t\t\treturn nil, nil, ctxerror.New(\"[Finalize] failed update validator info\").WithCause(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terr = errors.New(\"[Finalize] validator came back empty \" + common2.MustAddressToBech32(validator))\n\t\t\t\treturn nil, nil, ctxerror.New(\"[Finalize] failed getting validator info\").WithCause(err)\n\t\t\t}\n\t\t}\n\n\t\t// Set the LastEpochInCommittee field for all external validators in the upcoming epoch.\n\t\tnewShardState, err := header.GetShardState()\n\t\tif err != nil {\n\t\t\treturn nil, nil, ctxerror.New(\"[Finalize] failed to read shard state\").WithCause(err)\n\t\t}\n\t\tprocessed := make(map[common.Address]struct{})\n\t\tfor i := range newShardState.Shards {\n\t\t\tshard := newShardState.Shards[i]\n\t\t\tfor j := range shard.Slots {\n\t\t\t\tslot := shard.Slots[j]\n\t\t\t\tif slot.EffectiveStake != nil { // For external validator\n\t\t\t\t\t_, ok := processed[slot.EcdsaAddress]\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\tprocessed[slot.EcdsaAddress] = struct{}{}\n\t\t\t\t\t\twrapper := state.GetStakingInfo(slot.EcdsaAddress)\n\t\t\t\t\t\twrapper.LastEpochInCommittee = newShardState.Epoch\n\n\t\t\t\t\t\tif err := state.UpdateStakingInfo(slot.EcdsaAddress, wrapper); err != nil {\n\t\t\t\t\t\t\treturn nil, nil, ctxerror.New(\"[Finalize] failed update validator info\").WithCause(err)\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\theader.SetRoot(state.IntermediateRoot(chain.Config().IsS3(header.Epoch())))\n\treturn types.NewBlock(header, txs, receipts, outcxs, incxs, stks), payout, nil\n}", "func (c *ClaimPayment) TotalDue() decimal.Decimal {\n\ttotalDue := decimal.Zero\n\tfor _, sc := range c.ClaimsPayed {\n\t\ttotalDue = totalDue.Add(sc.EventSlot.Cost)\n\t}\n\treturn totalDue\n}", "func (pva PeriodicVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn pva.OriginalVesting.Sub(pva.GetVestedCoins(blockTime))\n}", "func FixFreezeLookupMigration(db *IndexerDb, state *MigrationState) error {\n\t// Technically with this query no transactions are needed, and the accounting state doesn't need to be locked.\n\tupdateQuery := \"INSERT INTO txn_participation (addr, round, intra) VALUES ($1, $2, $3) ON CONFLICT DO NOTHING\"\n\tquery := fmt.Sprintf(\"select decode(txn.txn->'txn'->>'fadd','base64'),round,intra from txn where typeenum = %d AND txn.txn->'txn'->'snd' != txn.txn->'txn'->'fadd'\", idb.TypeEnumAssetFreeze)\n\trows, err := db.db.Query(query)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to query transactions: %v\", err)\n\t}\n\tdefer rows.Close()\n\n\ttxprows := make([][]interface{}, 0)\n\n\t// Loop through all transactions and compute account data.\n\tdb.log.Print(\"loop through all freeze transactions\")\n\tfor rows.Next() {\n\t\tvar addr []byte\n\t\tvar round, intra uint64\n\t\terr = rows.Scan(&addr, &round, &intra)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error scanning row: %v\", err)\n\t\t}\n\n\t\ttxprows = append(txprows, []interface{}{addr, round, intra})\n\n\t\tif len(txprows) > 5000 {\n\t\t\terr = updateBatch(db, updateQuery, txprows)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"updating batch: %v\", err)\n\t\t\t}\n\t\t\ttxprows = txprows[:0]\n\t\t}\n\t}\n\n\tif rows.Err() != nil {\n\t\treturn fmt.Errorf(\"error while processing freeze transactions: %v\", rows.Err())\n\t}\n\n\t// Commit any leftovers\n\tif len(txprows) > 0 {\n\t\terr = updateBatch(db, updateQuery, txprows)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"updating batch: %v\", err)\n\t\t}\n\t}\n\n\t// Update migration state\n\treturn upsertMigrationState(db, state, true)\n}", "func calcHostRemoveCriteria(info storage.HostInfo, currentBlockHeight uint64) float64 {\n\ttimeDiff := float64(currentBlockHeight - info.FirstSeen)\n\tcriteria := uptimeCap - (uptimeCap-critIntercept)/(timeDiff/float64(critRemoveBase)+1)\n\treturn criteria\n}", "func (e *Event) CalculateTotalFee() {\n\tvar total float64\n\n\tfor _, reservation := range e.Reservations {\n\t\ttotal += reservation.totalFee()\n\t}\n\n\te.TotalFee = total\n}", "func (_DogsOfRome *DogsOfRomeCallerSession) Balance(arg0 common.Address) (*big.Int, error) {\n\treturn _DogsOfRome.Contract.Balance(&_DogsOfRome.CallOpts, arg0)\n}", "func (a *Account) CalculateBalance(confirms int) (btcutil.Amount, error) {\n\trpcc, err := accessClient()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tbs, err := rpcc.BlockStamp()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn a.TxStore.Balance(confirms, bs.Height)\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 TestDebitCampaignAccountWithEnoughRemainingDailyBudgetInMicroCents(t *testing.T) {\n\tb := NewRedisBanker(testDataAccess)\n\tcp := NewRedisCampaignProvider(testDataAccess, b)\n\n\tcampaignId := int64(313)\n\tbidCpmInMicroCents := int64(100)\n\tdailyBudgetInMicroCents := int64(100)\n\ttarget := rtb.Target{Type: rtb.Placement, Value: \"Words With Friends 2 iPad\"}\n\ttargets := []rtb.Target{target}\n\n\tdailyBudgetExpiration := time.Now().UTC().AddDate(0, 0, 1)\n\n\tamount := int64(32)\n\n\tcp.CreateCampaign(campaignId, bidCpmInMicroCents, dailyBudgetInMicroCents, targets)\n\n\texpectedRemainingDailyBudgetInMicroCents := dailyBudgetInMicroCents - amount\n\n\tb.SetRemainingDailyBudgetInMicroCents(campaignId, dailyBudgetInMicroCents, dailyBudgetExpiration)\n\n\tresult, err := cp.DebitCampaign(campaignId, amount, dailyBudgetExpiration)\n\n\tupdatedRemainingDailyBudgetInMicroCents := b.RemainingDailyBudgetInMicroCents(campaignId)\n\n\tif err != nil {\n\t\tt.Fail()\n\t}\n\n\tif result != expectedRemainingDailyBudgetInMicroCents {\n\t\tt.Fail()\n\t}\n\n\tif updatedRemainingDailyBudgetInMicroCents != expectedRemainingDailyBudgetInMicroCents {\n\t\tt.Fail()\n\t}\n}", "func GetBlockCumulativeGas(clientCtx client.Context, block *tmtypes.Block, idx int) uint64 {\n\tvar gasUsed uint64\n\ttxDecoder := clientCtx.TxConfig.TxDecoder()\n\n\tfor i := 0; i < idx && i < len(block.Txs); i++ {\n\t\ttxi, err := txDecoder(block.Txs[i])\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch tx := txi.(type) {\n\t\tcase *evmtypes.MsgEthereumTx:\n\t\t\tgasUsed += tx.GetGas()\n\t\tcase sdk.FeeTx:\n\t\t\tgasUsed += tx.GetGas()\n\t\t}\n\t}\n\treturn gasUsed\n}", "func (s *Store) Balance(minConf int, chainHeight int32) int64 {\n\tbal := int64(0)\n\tfor _, rt := range s.unspent {\n\t\tif confirmed(minConf, rt.Height(), chainHeight) {\n\t\t\ttx := s.txs[rt.blockTx()]\n\t\t\tmsgTx := tx.MsgTx()\n\t\t\ttxOut := msgTx.TxOut[rt.outpoint.Index]\n\t\t\tbal += txOut.Value\n\t\t}\n\t}\n\treturn bal\n}", "func (a *Account) CalculateBalance(confirms int) float64 {\n\tbs, err := GetCurBlock()\n\tif bs.Height == int32(btcutil.BlockHeightUnknown) || err != nil {\n\t\treturn 0.\n\t}\n\n\tbal := a.TxStore.Balance(confirms, bs.Height)\n\treturn float64(bal) / float64(btcutil.SatoshiPerBitcoin)\n}" ]
[ "0.6719768", "0.5626019", "0.5324699", "0.52189773", "0.5140744", "0.50596994", "0.5059033", "0.504977", "0.48822775", "0.48712832", "0.4870118", "0.48615333", "0.48471743", "0.4828697", "0.48089796", "0.4786879", "0.47522268", "0.4720129", "0.47145593", "0.47144145", "0.4701087", "0.46928984", "0.4690911", "0.46656278", "0.46534956", "0.46191686", "0.4610419", "0.46066105", "0.4583699", "0.45719275", "0.4566916", "0.45563477", "0.45557", "0.45552716", "0.4538513", "0.45368183", "0.45175794", "0.45020607", "0.4484064", "0.44784787", "0.44721258", "0.44609022", "0.44390386", "0.44390386", "0.4432514", "0.44055024", "0.43981206", "0.43944976", "0.43932492", "0.43769056", "0.4371576", "0.4370408", "0.43625018", "0.43522725", "0.43513757", "0.43500715", "0.43459055", "0.43447885", "0.43431884", "0.43398416", "0.43331942", "0.4315339", "0.43148404", "0.43121624", "0.43113363", "0.43068358", "0.4303899", "0.42985645", "0.4296866", "0.4288285", "0.4283617", "0.4281233", "0.4273122", "0.42724922", "0.42704847", "0.42652234", "0.4264584", "0.4262074", "0.42611495", "0.42578867", "0.4253606", "0.42450407", "0.42388657", "0.4231197", "0.4223479", "0.42224342", "0.42212832", "0.4202203", "0.42013258", "0.41999215", "0.41969192", "0.41968453", "0.41941792", "0.4191857", "0.41916093", "0.41892928", "0.4186268", "0.41820365", "0.41803595", "0.4175398" ]
0.80608404
0
updateDelegation returns an account with its delegation bookkeeping modified for clawback, given the current disposition of the account's bank and staking state. Also returns the modified amount to claw back. Computation steps: first, compute the total amount in bonded and unbonding states, used for BaseAccount bookkeeping; based on the old bookkeeping, determine the amount lost to slashing since origin; clip the amount to claw back to be at most the full funds in the account; first claw back the unbonded funds, then go after what's delegated; to the remaining delegated amount, add what's slashed; the "encumbered" (locked up and/or vesting) amount of this goes in DV; the remainder of the new delegated amount goes in DF.
updateDelegation возвращает аккаунт с измененными записями о делегировании для отбывания штрафа, учитывая текущее состояние банковского и стейкинг-аккаунта. Также возвращает измененную сумму для отбывания штрафа. Этапы вычисления: сначала вычисляется общая сумма в состоянии заблокированных и разблокированных средств, используемая для учета в BaseAccount; на основе старых записей определяется сумма, утерянная из-за штрафов с момента начального состояния; сумма для отбывания штрафа ограничивается максимальной суммой средств в аккаунте; сначала возвращаются средства в разблокированном состоянии, затем идет за тем, что было делегировано; к оставшейся сумме делегирования добавляется сумма, утерянная из-за штрафов; сумма, которая является "заблокированной" (заблокированной и/или с привязкой), идет в DV; оставшаяся часть новой суммы делегирования идет в DF.
func (va *ClawbackVestingAccount) updateDelegation(encumbered, toClawBack, bonded, unbonding, unbonded sdk.Coins) sdk.Coins { delegated := bonded.Add(unbonding...) oldDelegated := va.DelegatedVesting.Add(va.DelegatedFree...) slashed := oldDelegated.Sub(coinsMin(delegated, oldDelegated)) total := delegated.Add(unbonded...) toClawBack = coinsMin(toClawBack, total) // might have been slashed newDelegated := coinsMin(delegated, total.Sub(toClawBack)).Add(slashed...) va.DelegatedVesting = coinsMin(encumbered, newDelegated) va.DelegatedFree = newDelegated.Sub(va.DelegatedVesting) return toClawBack }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "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 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 (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 (_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 Keeper) WithdrawDelegationRewards(ctx sdk.Context, delAddr chainTypes.AccountID, valAddr chainTypes.AccountID) (Coins, error) {\n\n\tval := k.stakingKeeper.Validator(ctx, valAddr)\n\tctx.Logger().Debug(\"WithdrawDelegationRewards\", \"val:\", val)\n\tif val == nil {\n\t\treturn nil, types.ErrNoValidatorDistInfo\n\t}\n\n\tdel := k.stakingKeeper.Delegation(ctx, delAddr, valAddr)\n\tctx.Logger().Debug(\"WithdrawDelegationRewards\", \"del:\", del)\n\tif del == nil {\n\t\treturn nil, types.ErrEmptyDelegationDistInfo\n\t}\n\n\t// withdraw rewards\n\trewards, err := k.withdrawDelegationRewards(ctx, val, del)\n\tif err != nil {\n\t\tctx.Logger().Debug(\"WithdrawDelegationRewards\", \"err:\", err)\n\t\treturn nil, err\n\t}\n\tctx.Logger().Debug(\"WithdrawDelegationRewards\", \"rewards:\", rewards)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeWithdrawRewards,\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, rewards.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, valAddr.String()),\n\t\t),\n\t)\n\n\t// reinitialize the delegation\n\tk.initializeDelegation(ctx, valAddr, delAddr)\n\treturn rewards, nil\n}", "func (va *ClawbackVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tva.BaseVestingAccount.TrackDelegation(balance, va.GetVestingCoins(blockTime), amount)\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 (_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 (dva *DelayedVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tdva.BaseVestingAccount.TrackDelegation(balance, dva.GetVestingCoins(blockTime), 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 (_DelegationController *DelegationControllerSession) GetAndUpdateDelegatedAmount(holder common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateDelegatedAmount(&_DelegationController.TransactOpts, holder)\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 (cva *ContinuousVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tcva.BaseVestingAccount.TrackDelegation(balance, cva.GetVestingCoins(blockTime), amount)\n}", "func (_DelegationController *DelegationControllerTransactorSession) GetAndUpdateDelegatedAmount(holder common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateDelegatedAmount(&_DelegationController.TransactOpts, holder)\n}", "func (pva *PeriodicVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tpva.BaseVestingAccount.TrackDelegation(balance, pva.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 (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 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 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 (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 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 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 (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 (va *ClawbackVestingAccount) clawback(ctx sdk.Context, dest sdk.AccAddress, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) error {\n\t// Compute the clawback based on the account state only, and update account\n\ttoClawBack := va.computeClawback(ctx.BlockTime().Unix())\n\tif toClawBack.IsZero() {\n\t\treturn nil\n\t}\n\taddr := va.GetAddress()\n\tbondDenom := sk.BondDenom(ctx)\n\n\t// Compute the clawback based on bank balance and delegation, and update account\n\tencumbered := va.GetVestingCoins(ctx.BlockTime())\n\tbondedAmt := sk.GetDelegatorBonded(ctx, addr)\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, addr)\n\tbonded := sdk.NewCoins(sdk.NewCoin(bondDenom, bondedAmt))\n\tunbonding := sdk.NewCoins(sdk.NewCoin(bondDenom, unbondingAmt))\n\tunbonded := bk.GetAllBalances(ctx, addr)\n\ttoClawBack = va.updateDelegation(encumbered, toClawBack, bonded, unbonding, unbonded)\n\n\t// Write now now so that the bank module sees unvested tokens are unlocked.\n\t// Note that all store writes are aborted if there is a panic, so there is\n\t// no danger in writing incomplete results.\n\tak.SetAccount(ctx, va)\n\n\t// Now that future vesting events (and associated lockup) are removed,\n\t// the balance of the account is unlocked and can be freely transferred.\n\tspendable := bk.SpendableCoins(ctx, addr)\n\ttoXfer := coinsMin(toClawBack, spendable)\n\terr := bk.SendCoins(ctx, addr, dest, toXfer)\n\tif err != nil {\n\t\treturn err // shouldn't happen, given spendable check\n\t}\n\ttoClawBack = toClawBack.Sub(toXfer)\n\n\t// We need to traverse the staking data structures to update the\n\t// vesting account bookkeeping, and to recover more funds if necessary.\n\t// Staking is the only way unvested tokens should be missing from the bank balance.\n\n\t// If we need more, transfer UnbondingDelegations.\n\twant := toClawBack.AmountOf(bondDenom)\n\tunbondings := sk.GetUnbondingDelegations(ctx, addr, math.MaxUint16)\n\tfor _, unbonding := range unbondings {\n\t\tvalAddr, err := sdk.ValAddressFromBech32(unbonding.ValidatorAddress)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\ttransferred := sk.TransferUnbonding(ctx, addr, dest, valAddr, want)\n\t\twant = want.Sub(transferred)\n\t\tif !want.IsPositive() {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// If we need more, transfer Delegations.\n\tif want.IsPositive() {\n\t\tdelegations := sk.GetDelegatorDelegations(ctx, addr, math.MaxUint16)\n\t\tfor _, delegation := range delegations {\n\t\t\tvalidatorAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err) // shouldn't happen\n\t\t\t}\n\t\t\tvalidator, found := sk.GetValidator(ctx, validatorAddr)\n\t\t\tif !found {\n\t\t\t\t// validator has been removed\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\twantShares, err := validator.SharesFromTokensTruncated(want)\n\t\t\tif err != nil {\n\t\t\t\t// validator has no tokens\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttransferredShares := sk.TransferDelegation(ctx, addr, dest, delegation.GetValidatorAddr(), wantShares)\n\t\t\t// to be conservative in what we're clawing back, round transferred shares up\n\t\t\ttransferred := validator.TokensFromSharesRoundUp(transferredShares).RoundInt()\n\t\t\twant = want.Sub(transferred)\n\t\t\tif !want.IsPositive() {\n\t\t\t\t// Could be slightly negative, due to rounding?\n\t\t\t\t// Don't think so, due to the precautions above.\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// If we've transferred everything and still haven't transferred the desired clawback amount,\n\t// then the account must have most some unvested tokens from slashing.\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 (va ClawbackVestingAccount) postReward(ctx sdk.Context, reward sdk.Coins, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) {\n\t// Find the scheduled amount of vested and unvested staking tokens\n\tbondDenom := sk.BondDenom(ctx)\n\tvested := ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, ctx.BlockTime().Unix()).AmountOf(bondDenom)\n\tunvested := va.OriginalVesting.AmountOf(bondDenom).Sub(vested)\n\n\tif unvested.IsZero() {\n\t\t// no need to adjust the vesting schedule\n\t\treturn\n\t}\n\n\tif vested.IsZero() {\n\t\t// all staked tokens must be unvested\n\t\tva.distributeReward(ctx, ak, bondDenom, reward)\n\t\treturn\n\t}\n\n\t// Find current split of account balance on staking axis\n\tbonded := sk.GetDelegatorBonded(ctx, va.GetAddress())\n\tunbonding := sk.GetDelegatorUnbonding(ctx, va.GetAddress())\n\tdelegated := bonded.Add(unbonding)\n\n\t// discover what has been slashed and remove from delegated amount\n\toldDelegated := va.DelegatedVesting.AmountOf(bondDenom).Add(va.DelegatedFree.AmountOf(bondDenom))\n\tslashed := oldDelegated.Sub(intMin(oldDelegated, delegated))\n\tdelegated = delegated.Sub(intMin(delegated, slashed))\n\n\t// Prefer delegated tokens to be unvested\n\tunvested = intMin(unvested, delegated)\n\tvested = delegated.Sub(unvested)\n\n\t// Compute the unvested amount of reward and add to vesting schedule\n\tif unvested.IsZero() {\n\t\treturn\n\t}\n\tif vested.IsZero() {\n\t\tva.distributeReward(ctx, ak, bondDenom, reward)\n\t\treturn\n\t}\n\tunvestedRatio := unvested.ToDec().QuoTruncate(bonded.ToDec()) // round down\n\tunvestedReward := scaleCoins(reward, unvestedRatio)\n\tva.distributeReward(ctx, ak, bondDenom, unvestedReward)\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 (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 (vva *ValidatorVestingAccount) TrackDelegation(blockTime time.Time, amount sdk.Coins) {\n\tvva.BaseVestingAccount.TrackDelegation(vva.GetVestingCoins(blockTime), amount)\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 (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 (a *Accounting) callUpdateAccounting() (modules.AccountingInfo, error) {\n\tvar ai modules.AccountingInfo\n\n\t// Get Renter information\n\t//\n\t// NOTE: renter is optional so can be nil\n\tvar renterErr error\n\tif a.staticRenter != nil {\n\t\tvar spending modules.ContractorSpending\n\t\tspending, renterErr = a.staticRenter.PeriodSpending()\n\t\tif renterErr == nil {\n\t\t\t_, _, unspentUnallocated := spending.SpendingBreakdown()\n\t\t\tai.Renter.UnspentUnallocated = unspentUnallocated\n\t\t\tai.Renter.WithheldFunds = spending.WithheldFunds\n\t\t}\n\t}\n\n\t// Get Wallet information\n\tsc, sf, _, walletErr := a.staticWallet.ConfirmedBalance()\n\tif walletErr == nil {\n\t\tai.Wallet.ConfirmedSiacoinBalance = sc\n\t\tai.Wallet.ConfirmedSiafundBalance = sf\n\t}\n\n\t// Update the Accounting state\n\terr := errors.Compose(renterErr, walletErr)\n\tif err == nil {\n\t\ta.mu.Lock()\n\t\ta.persistence.Renter = ai.Renter\n\t\ta.persistence.Wallet = ai.Wallet\n\t\ta.persistence.Timestamp = time.Now().Unix()\n\t\ta.mu.Unlock()\n\t}\n\treturn ai, err\n}", "func updateAccountData(address types.Address, round uint32, assetID uint32, stxn types.SignedTxnWithAD, accountData *m7AccountData, assetDataMap map[uint32]createClose) {\n\t// Transactions are ordered most recent to oldest, so this makes sure created is set to the\n\t// oldest transaction.\n\taccountData.account.createdValid = true\n\taccountData.account.created = uint32(round)\n\n\t// When the account is closed rewards reset to zero.\n\t// Because transactions are newest to oldest, stop accumulating once we see a close.\n\tif !accountData.account.closedValid {\n\t\tif accounting.AccountCloseTxn(address, stxn) {\n\t\t\taccountData.account.closedValid = true\n\t\t\taccountData.account.closed = uint32(round)\n\n\t\t\tif !accountData.account.deletedValid {\n\t\t\t\taccountData.account.deletedValid = true\n\t\t\t\taccountData.account.deleted = true\n\t\t\t}\n\t\t} else {\n\t\t\tif !accountData.account.deletedValid {\n\t\t\t\taccountData.account.deletedValid = true\n\t\t\t\taccountData.account.deleted = false\n\t\t\t}\n\n\t\t\tif stxn.Txn.Sender == address {\n\t\t\t\taccountData.cumulativeRewards += stxn.ApplyData.SenderRewards\n\t\t\t}\n\n\t\t\tif stxn.Txn.Receiver == address {\n\t\t\t\taccountData.cumulativeRewards += stxn.ApplyData.ReceiverRewards\n\t\t\t}\n\n\t\t\tif stxn.Txn.CloseRemainderTo == address {\n\t\t\t\taccountData.cumulativeRewards += stxn.ApplyData.CloseRewards\n\t\t\t}\n\t\t}\n\t}\n\n\tif accounting.AssetCreateTxn(stxn) {\n\t\tmaybeInitializeAdditionalAccountData(accountData)\n\t\tcc := updateCreate(round, assetDataMap[assetID])\n\t\tassetDataMap[assetID] = cc\n\t\taccountData.additional.asset[assetID] = struct{}{}\n\t\t// Special handling of asset holding since creating and deleting an asset also creates and\n\t\t// deletes an asset holding for the creator, but a different manager address can delete an\n\t\t// asset.\n\t\taccountData.assetHolding[assetID] = cc\n\t}\n\n\tif accounting.AssetDestroyTxn(stxn) {\n\t\tassetDataMap[assetID] = updateClose(round, assetDataMap[assetID])\n\t}\n\n\tif accounting.AssetOptInTxn(stxn) {\n\t\taccountData.assetHolding[assetID] = updateCreate(round, accountData.assetHolding[assetID])\n\t}\n\n\tif accounting.AssetOptOutTxn(stxn) && (stxn.Txn.Sender == address) {\n\t\taccountData.assetHolding[assetID] = updateClose(round, accountData.assetHolding[assetID])\n\t}\n\n\tif accounting.AppCreateTxn(stxn) {\n\t\tmaybeInitializeAdditionalAccountData(accountData)\n\t\taccountData.additional.app[assetID] = updateCreate(round, accountData.additional.app[assetID])\n\t}\n\n\tif accounting.AppDestroyTxn(stxn) {\n\t\tmaybeInitializeAdditionalAccountData(accountData)\n\t\taccountData.additional.app[assetID] = updateClose(round, accountData.additional.app[assetID])\n\t}\n\n\tif accounting.AppOptInTxn(stxn) {\n\t\tmaybeInitializeAdditionalAccountData(accountData)\n\t\taccountData.additional.appLocal[assetID] =\n\t\t\tupdateCreate(round, accountData.additional.appLocal[assetID])\n\t}\n\n\tif accounting.AppOptOutTxn(stxn) {\n\t\tmaybeInitializeAdditionalAccountData(accountData)\n\t\taccountData.additional.appLocal[assetID] =\n\t\t\tupdateClose(round, accountData.additional.appLocal[assetID])\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 (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 (o OfflineNotaryRepository) AddDelegation(data.RoleName, []data.PublicKey, []string) error {\n\treturn nil\n}", "func (k Keeper) Delegation(ctx sdk.Context, addrDel sdk.AccAddress, addrVal sdk.ValAddress) exported.DelegationI {\n\treturn nil\n}", "func (_DelegationController *DelegationControllerSession) Confiscate(validatorId *big.Int, amount *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.Confiscate(&_DelegationController.TransactOpts, validatorId, amount)\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 (t *ManageAccount) updateAccountBalance(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\n\tvar jsonResp string\n\tvar err error\n\n\t//set amountPaid\n\tamountPaid := args[2]\n\n\t// input sanitation\n\tif len(args) != 4 {\n\t\terrMsg := \"{ \\\"message\\\" : \\\"Incorrect number of arguments. Expecting \\\"Customer Account Id, Service Provider Account Id, Amount paid\\\" and \\\" operation\\\" as an argument.\\\", \\\"code\\\" : \\\"503\\\"}\"\n\t\terr = stub.SetEvent(\"errEvent\", []byte(errMsg))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfmt.Println(errMsg)\t\n\t\treturn nil, errors.New(errMsg)\n\t}\n\n\tfmt.Println(\"Updating the account balance of\"+ args[0] + \" and \" + args[1])\n\t// convert string to float\n\t_amountPaid, _ := strconv.ParseFloat(amountPaid, 64)\n\toperation := args[3]\n\taccount := Account{}\n\tfor i := 0; i < 2; i++ {\n\t\taccountAsBytes, err := stub.GetState(args[i])\t\t\t\t\t\t\t\t\t//get the var from chaincode state\n\t\tif err != nil {\n\t\t\tjsonResp = \"{\\\"Error\\\":\\\"Failed to get state for \" + args[i] + \"\\\"}\"\n\t\t\treturn nil, errors.New(jsonResp)\n\t\t}\n\t\tjson.Unmarshal(accountAsBytes, &account)\n\t\tif account.AccountOwnerId == args[i]{\n\t\t\tif account.AccountName == \"Customer\" {\n\t\t\t\tfmt.Println(\"Customer Account found with account Owner Id : \" + args[i])\n\t\t\t\tfmt.Println(account);\n\t\t\t\tif operation == \"Initial\" || operation == \"Final\" {\n\t\t\t\t\taccount.AccountBalance = account.AccountBalance - _amountPaid\n\t\t\t\t}else{\n\t\t\t\t\taccount.AccountBalance = account.AccountBalance + _amountPaid\n\t\t\t\t}\n\t\t\t} else if account.AccountName == \"Service Provider\" {\n\t\t\t\tfmt.Println(\"Service Provider Account found with account Owner Id : \" + args[i])\n\t\t\t\tfmt.Println(account);\n\t\t\t\tif operation == \"Final\" || operation == \"Initial\"{\n\t\t\t\t\taccount.AccountBalance = account.AccountBalance + _amountPaid\n\t\t\t\t}else {\n\t\t\t\t\taccount.AccountBalance = account.AccountBalance - _amountPaid\n\t\t\t\t}\n\t\t\t}\n\t\t}else {\n\t\t\terrMsg := \"{ \\\"message\\\" : \\\"\"+ args[i]+ \" Not Found.\\\", \\\"code\\\" : \\\"503\\\"}\"\n\t\t\terr = stub.SetEvent(\"errEvent\", []byte(errMsg))\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tfmt.Println(errMsg); \n\t\t}\n\t\t\n\t\t//build the Payment json string\n\t\taccountJson := &Account{account.AccountOwnerId,account.AccountName,account.AccountBalance}\n\t\t// convert *Account to []byte\n\t\taccountJsonasBytes, err := json.Marshal(accountJson)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t//store account Owner Id as key\n\t\terr = stub.PutState(account.AccountOwnerId, accountJsonasBytes)\t\t\t\t\t\t\t\t\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// event message to set on successful account updation\n\t\ttosend := \"{ \\\"Account Owner Id\\\" : \\\"\"+account.AccountOwnerId+\"\\\", \\\"message\\\" : \\\"Account updated succcessfully\\\", \\\"code\\\" : \\\"200\\\"}\"\n\t\terr = stub.SetEvent(\"evtsender\", []byte(tosend))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfmt.Println(tosend); \t\n\t}\n\tfmt.Println(\"Account balance Updated Successfully.\")\n\treturn nil, nil\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 (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 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 (_DelegationController *DelegationControllerTransactorSession) Confiscate(validatorId *big.Int, amount *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.Confiscate(&_DelegationController.TransactOpts, validatorId, amount)\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 (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 (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 rewardAndSlash(ctx contract.Context, cachedDelegations *CachedDposStorage, state *State) ([]*DelegationResult, error) {\n\tformerValidatorTotals := make(map[string]loom.BigUInt)\n\tdelegatorRewards := make(map[string]*loom.BigUInt)\n\tdistributedRewards := common.BigZero()\n\n\tdelegations, err := cachedDelegations.loadDelegationList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, validator := range state.Validators {\n\t\tcandidate := GetCandidateByPubKey(ctx, validator.PubKey)\n\n\t\tif candidate == nil {\n\t\t\tctx.Logger().Info(\"Attempted to reward validator no longer on candidates list.\", \"validator\", validator)\n\t\t\tcontinue\n\t\t}\n\n\t\tcandidateAddress := loom.UnmarshalAddressPB(candidate.Address)\n\t\tvalidatorKey := candidateAddress.String()\n\t\tstatistic, _ := GetStatistic(ctx, candidateAddress)\n\n\t\tif statistic == nil {\n\t\t\tdelegatorRewards[validatorKey] = common.BigZero()\n\t\t\tformerValidatorTotals[validatorKey] = *common.BigZero()\n\t\t} else {\n\t\t\t// If a validator is jailed, don't calculate and distribute rewards\n\t\t\tif ctx.FeatureEnabled(features.DPOSVersion3_3, false) {\n\t\t\t\tif statistic.Jailed {\n\t\t\t\t\tdelegatorRewards[validatorKey] = common.BigZero()\n\t\t\t\t\tformerValidatorTotals[validatorKey] = *common.BigZero()\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\t// If a validator's SlashPercentage is 0, the validator is\n\t\t\t// rewarded for avoiding faults during the last slashing period\n\t\t\tif common.IsZero(statistic.SlashPercentage.Value) {\n\t\t\t\tdistributionTotal := calculateRewards(statistic.DelegationTotal.Value, state.Params, state.TotalValidatorDelegations.Value)\n\n\t\t\t\t// The validator share, equal to validator_fee * total_validotor_reward\n\t\t\t\t// is to be split between the referrers and the validator\n\t\t\t\tvalidatorShare := CalculateFraction(loom.BigUInt{big.NewInt(int64(candidate.Fee))}, distributionTotal)\n\n\t\t\t\t// delegatorsShare is what fraction of the total rewards will be\n\t\t\t\t// distributed to delegators\n\t\t\t\tdelegatorsShare := common.BigZero()\n\t\t\t\tdelegatorsShare.Sub(&distributionTotal, &validatorShare)\n\t\t\t\tdelegatorRewards[validatorKey] = delegatorsShare\n\n\t\t\t\t// Distribute rewards to referrers\n\t\t\t\tfor _, d := range delegations {\n\t\t\t\t\tif loom.UnmarshalAddressPB(d.Validator).Compare(loom.UnmarshalAddressPB(candidate.Address)) == 0 {\n\t\t\t\t\t\tdelegation, err := GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\t\t\t\t\t// if the delegation is not found OR if the delegation\n\t\t\t\t\t\t// has no referrer, we do not need to attempt to\n\t\t\t\t\t\t// distribute the referrer rewards\n\t\t\t\t\t\tif err == contract.ErrNotFound || len(delegation.Referrer) == 0 {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t} else if err != nil {\n\t\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// if referrer is not found, do not distribute the reward\n\t\t\t\t\t\treferrerAddress := getReferrer(ctx, delegation.Referrer)\n\t\t\t\t\t\tif referrerAddress == nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// calculate referrerReward\n\t\t\t\t\t\treferrerReward := calculateRewards(delegation.Amount.Value, state.Params, state.TotalValidatorDelegations.Value)\n\t\t\t\t\t\treferrerReward = CalculateFraction(loom.BigUInt{big.NewInt(int64(candidate.Fee))}, referrerReward)\n\t\t\t\t\t\treferrerReward = CalculateFraction(defaultReferrerFee, referrerReward)\n\n\t\t\t\t\t\t// referrer fees are delegater to limbo validator\n\t\t\t\t\t\tdistributedRewards.Add(distributedRewards, &referrerReward)\n\t\t\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, LimboValidatorAddress(ctx).MarshalPB(), referrerAddress, referrerReward)\n\n\t\t\t\t\t\t// any referrer bonus amount is subtracted from the validatorShare\n\t\t\t\t\t\tvalidatorShare.Sub(&validatorShare, &referrerReward)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tdistributedRewards.Add(distributedRewards, &validatorShare)\n\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, candidate.Address, candidate.Address, validatorShare)\n\n\t\t\t\t// If a validator has some non-zero WhitelistAmount,\n\t\t\t\t// calculate the validator's reward based on whitelist amount\n\t\t\t\tif !common.IsZero(statistic.WhitelistAmount.Value) {\n\t\t\t\t\tamount := calculateWeightedWhitelistAmount(*statistic)\n\t\t\t\t\twhitelistDistribution := calculateShare(amount, statistic.DelegationTotal.Value, *delegatorsShare)\n\t\t\t\t\t// increase a delegator's distribution\n\t\t\t\t\tdistributedRewards.Add(distributedRewards, &whitelistDistribution)\n\t\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, candidate.Address, candidate.Address, whitelistDistribution)\n\t\t\t\t}\n\n\t\t\t\t// Keeping track of cumulative distributed rewards by adding\n\t\t\t\t// every validator's total rewards to\n\t\t\t\t// `state.TotalRewardDistribution`\n\t\t\t\t// NOTE: because we round down in every `calculateRewards` call,\n\t\t\t\t// we expect `state.TotalRewardDistribution` to be a slight\n\t\t\t\t// overestimate of what was actually distributed. We could be\n\t\t\t\t// exact with our record keeping by incrementing\n\t\t\t\t// `state.TotalRewardDistribution` each time\n\t\t\t\t// `IncreaseRewardDelegation` is called, but because we will not\n\t\t\t\t// use `state.TotalRewardDistributions` as part of any invariants,\n\t\t\t\t// we will live with this situation.\n\t\t\t\tif !ctx.FeatureEnabled(features.DPOSVersion3_1, false) {\n\t\t\t\t\tstate.TotalRewardDistribution.Value.Add(&state.TotalRewardDistribution.Value, &distributionTotal)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif err := slashValidatorDelegations(ctx, cachedDelegations, statistic, candidateAddress); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tif err := SetStatistic(ctx, statistic); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tformerValidatorTotals[validatorKey] = statistic.DelegationTotal.Value\n\t\t}\n\t}\n\n\tnewDelegationTotals, err := distributeDelegatorRewards(ctx, cachedDelegations, formerValidatorTotals, delegatorRewards, distributedRewards)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif ctx.FeatureEnabled(features.DPOSVersion3_1, false) {\n\t\tstate.TotalRewardDistribution.Value.Add(&state.TotalRewardDistribution.Value, distributedRewards)\n\t}\n\n\tdelegationResults := make([]*DelegationResult, 0, len(newDelegationTotals))\n\tfor validator := range newDelegationTotals {\n\t\tdelegationResults = append(delegationResults, &DelegationResult{\n\t\t\tValidatorAddress: loom.MustParseAddress(validator),\n\t\t\tDelegationTotal: *newDelegationTotals[validator],\n\t\t})\n\t}\n\tsort.Sort(byDelegationTotal(delegationResults))\n\n\treturn delegationResults, 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 TestSlashBoth(t *testing.T) {\n\tapp, ctx, addrDels, addrVals := bootstrapSlashTest(t, 10)\n\tfraction := sdk.NewDecWithPrec(5, 1)\n\tbondDenom := app.StakingKeeper.BondDenom(ctx)\n\n\t// set a redelegation with expiration timestamp beyond which the\n\t// redelegation shouldn't be slashed\n\trdATokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 6)\n\trdA := types.NewRedelegation(addrDels[0], addrVals[0], addrVals[1], 11,\n\t\ttime.Unix(0, 0), rdATokens,\n\t\trdATokens.ToDec())\n\tapp.StakingKeeper.SetRedelegation(ctx, rdA)\n\n\t// set the associated delegation\n\tdelA := types.NewDelegation(addrDels[0], addrVals[1], rdATokens.ToDec())\n\tapp.StakingKeeper.SetDelegation(ctx, delA)\n\n\t// set an unbonding delegation with expiration timestamp (beyond which the\n\t// unbonding delegation shouldn't be slashed)\n\tubdATokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 4)\n\tubdA := types.NewUnbondingDelegation(addrDels[0], addrVals[0], 11,\n\t\ttime.Unix(0, 0), ubdATokens)\n\tapp.StakingKeeper.SetUnbondingDelegation(ctx, ubdA)\n\n\tbondedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, rdATokens.MulRaw(2)))\n\tnotBondedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, ubdATokens))\n\n\t// update bonded tokens\n\tbondedPool := app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool := app.StakingKeeper.GetNotBondedPool(ctx)\n\n\trequire.NoError(t, simapp.FundModuleAccount(app.BankKeeper, ctx, bondedPool.GetName(), bondedCoins))\n\trequire.NoError(t, simapp.FundModuleAccount(app.BankKeeper, ctx, notBondedPool.GetName(), notBondedCoins))\n\n\tapp.AccountKeeper.SetModuleAccount(ctx, bondedPool)\n\tapp.AccountKeeper.SetModuleAccount(ctx, notBondedPool)\n\n\toldBonded := app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\toldNotBonded := app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\t// slash validator\n\tctx = ctx.WithBlockHeight(12)\n\tvalidator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(PKs[0]))\n\trequire.True(t, found)\n\tconsAddr0 := sdk.ConsAddress(PKs[0].Address())\n\tapp.StakingKeeper.Slash(ctx, consAddr0, 10, 10, fraction)\n\n\tburnedNotBondedAmount := fraction.MulInt(ubdATokens).TruncateInt()\n\tburnedBondAmount := app.StakingKeeper.TokensFromConsensusPower(ctx, 10).ToDec().Mul(fraction).TruncateInt()\n\tburnedBondAmount = burnedBondAmount.Sub(burnedNotBondedAmount)\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(burnedBondAmount), bondedPoolBalance))\n\n\tnotBondedPoolBalance := app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldNotBonded.Sub(burnedNotBondedAmount), notBondedPoolBalance))\n\n\t// read updating redelegation\n\trdA, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])\n\trequire.True(t, found)\n\trequire.Len(t, rdA.Entries, 1)\n\t// read updated validator\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(PKs[0]))\n\trequire.True(t, found)\n\t// power not decreased, all stake was bonded since\n\trequire.Equal(t, int64(10), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))\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 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 AnnualBalanceUpdate(balance float64) float64 {\n\treturn balance + Interest(balance)\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 CalculateTotalPayout(delegatedContract DelegatedContract) DelegatedContract{\n for _, contract := range delegatedContract.Contracts{\n delegatedContract.TotalPayout = delegatedContract.TotalPayout + contract.NetPayout\n }\n return delegatedContract\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 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 (_Bindings *BindingsSession) RepayBorrowBehalf(borrower common.Address) (*types.Transaction, error) {\n\treturn _Bindings.Contract.RepayBorrowBehalf(&_Bindings.TransactOpts, borrower)\n}", "func (k Keeper) ClaimDelegatorReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tclaim, found := k.GetDelegatorClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tsyncedClaim, err := k.SynchronizeDelegatorClaim(ctx, claim)\n\tif err != nil {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr = k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetDelegatorClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn 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 (_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 (wallet *Wallet) refreshWallet(acc *account.Account, adr *wallet_address.WalletAddress) (err error) {\n\n\tif acc == nil {\n\t\treturn\n\t}\n\n\tif adr.DelegatedStake != nil && acc.DelegatedStake == nil {\n\t\tadr.DelegatedStake = nil\n\t\treturn\n\t}\n\n\tif (adr.DelegatedStake != nil && acc.DelegatedStake != nil && !bytes.Equal(adr.DelegatedStake.PublicKeyHash, acc.DelegatedStake.DelegatedPublicKeyHash)) ||\n\t\t(adr.DelegatedStake == nil && acc.DelegatedStake != nil) {\n\n\t\tif adr.IsMine {\n\n\t\t\tif acc.DelegatedStake != nil {\n\n\t\t\t\tlastKnownNonce := uint32(0)\n\t\t\t\tif adr.DelegatedStake != nil {\n\t\t\t\t\tlastKnownNonce = adr.DelegatedStake.LastKnownNonce\n\t\t\t\t}\n\n\t\t\t\tvar delegatedStake *wallet_address.WalletAddressDelegatedStake\n\t\t\t\tif delegatedStake, err = adr.FindDelegatedStake(uint32(acc.Nonce), lastKnownNonce, acc.DelegatedStake.DelegatedPublicKeyHash); err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tif delegatedStake != nil {\n\t\t\t\t\tadr.DelegatedStake = delegatedStake\n\t\t\t\t\twallet.forging.Wallet.AddWallet(adr.DelegatedStake.PrivateKey.Key, adr.Address.PublicKeyHash)\n\t\t\t\t\treturn wallet.saveWalletAddress(adr)\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tadr.DelegatedStake = nil\n\t\twallet.forging.Wallet.AddWallet(nil, adr.Address.PublicKeyHash)\n\t\treturn wallet.saveWalletAddress(adr)\n\t}\n\n\treturn\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 (m *Mantle) replenishBalance(w *botWallet) {\n\t// Get the Balance from the user in case it changed while while this note\n\t// was in the notification pipeline.\n\tbal, err := m.AssetBalance(w.assetID)\n\tif err != nil {\n\t\tm.fatalError(\"error updating %s balance: %v\", w.symbol, err)\n\t\treturn\n\t}\n\n\tm.log.Debugf(\"Balance note received for %s (minFunds = %s, maxFunds = %s): %s\",\n\t\tw.symbol, valString(w.minFunds), valString(w.maxFunds), mustJSON(bal))\n\n\teffectiveMax := w.maxFunds + (w.maxFunds - w.minFunds)\n\n\tif bal.Available < w.minFunds {\n\t\tchunk := (w.maxFunds - bal.Available) / uint64(w.numCoins)\n\t\tfor i := 0; i < w.numCoins; i++ {\n\t\t\tm.log.Debugf(\"Requesting %s from %s alpha node\", valString(chunk), w.symbol)\n\t\t\tcmdOut := <-harnessCtl(w.symbol, \"./alpha\", \"sendtoaddress\", w.address, valString(chunk))\n\t\t\tif cmdOut.err != nil {\n\t\t\t\tm.fatalError(\"error refreshing balance for %s: %v\", w.symbol, cmdOut.err)\n\t\t\t}\n\t\t}\n\t} else if bal.Available > effectiveMax {\n\t\t// Send some back to the alpha address.\n\t\tamt := bal.Available - w.maxFunds\n\t\tm.log.Debugf(\"Sending %s back to %s alpha node\", valString(amt), w.symbol)\n\t\t_, err := m.Withdraw(pass, w.assetID, amt, returnAddress(w.symbol, alpha))\n\t\tif err != nil {\n\t\t\tm.fatalError(\"failed to withdraw funds to alpha: %v\", err)\n\t\t}\n\t}\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 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 (k Keeper) RepayPrincipal(ctx sdk.Context, owner sdk.AccAddress, denom string, payment sdk.Coins) error {\n\t// validation\n\tcdp, found := k.GetCdpByOwnerAndDenom(ctx, owner, denom)\n\tif !found {\n\t\treturn sdkerrors.Wrapf(types.ErrCdpNotFound, \"owner %s, denom %s\", owner, denom)\n\t}\n\n\terr := k.ValidatePaymentCoins(ctx, cdp, payment, cdp.Principal.Add(cdp.AccumulatedFees...))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// calculate fee and principal payment\n\tfeePayment, principalPayment := k.calculatePayment(ctx, cdp.Principal.Add(cdp.AccumulatedFees...), cdp.AccumulatedFees, payment)\n\n\t// send the payment from the sender to the cpd module\n\terr = k.supplyKeeper.SendCoinsFromAccountToModule(ctx, owner, types.ModuleName, feePayment.Add(principalPayment...))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// burn the payment coins\n\terr = k.supplyKeeper.BurnCoins(ctx, types.ModuleName, feePayment.Add(principalPayment...))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// burn the corresponding amount of debt coins\n\tcdpDebt := k.getModAccountDebt(ctx, types.ModuleName)\n\tpaymentAmount := sdk.ZeroInt()\n\tfor _, c := range feePayment.Add(principalPayment...) {\n\t\tpaymentAmount = paymentAmount.Add(c.Amount)\n\t}\n\tcoinsToBurn := sdk.NewCoins(sdk.NewCoin(k.GetDebtDenom(ctx), paymentAmount))\n\tif paymentAmount.GT(cdpDebt) {\n\t\tcoinsToBurn = sdk.NewCoins(sdk.NewCoin(k.GetDebtDenom(ctx), cdpDebt))\n\t}\n\terr = k.BurnDebtCoins(ctx, types.ModuleName, k.GetDebtDenom(ctx), coinsToBurn)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// emit repayment event\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeCdpRepay,\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, feePayment.Add(principalPayment...).String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyCdpID, fmt.Sprintf(\"%d\", cdp.ID)),\n\t\t),\n\t)\n\n\t// remove the old collateral:debt ratio index\n\toldCollateralToDebtRatio := k.CalculateCollateralToDebtRatio(ctx, cdp.Collateral, cdp.Principal.Add(cdp.AccumulatedFees...))\n\tk.RemoveCdpCollateralRatioIndex(ctx, denom, cdp.ID, oldCollateralToDebtRatio)\n\n\t// update cdp state\n\tif !principalPayment.IsZero() {\n\t\tcdp.Principal = cdp.Principal.Sub(principalPayment)\n\t}\n\tcdp.AccumulatedFees = cdp.AccumulatedFees.Sub(feePayment)\n\tcdp.FeesUpdated = ctx.BlockTime()\n\n\t// decrement the total principal for the input collateral type\n\tk.DecrementTotalPrincipal(ctx, denom, feePayment.Add(principalPayment...))\n\n\t// if the debt is fully paid, return collateral to depositors,\n\t// and remove the cdp and indexes from the store\n\tif cdp.Principal.IsZero() && cdp.AccumulatedFees.IsZero() {\n\t\tk.ReturnCollateral(ctx, cdp)\n\t\tk.DeleteCDP(ctx, cdp)\n\t\tk.RemoveCdpOwnerIndex(ctx, cdp)\n\n\t\t// emit cdp close event\n\t\tctx.EventManager().EmitEvent(\n\t\t\tsdk.NewEvent(\n\t\t\t\ttypes.EventTypeCdpClose,\n\t\t\t\tsdk.NewAttribute(types.AttributeKeyCdpID, fmt.Sprintf(\"%d\", cdp.ID)),\n\t\t\t),\n\t\t)\n\t\treturn nil\n\t}\n\n\t// set cdp state and update indexes\n\tcollateralToDebtRatio := k.CalculateCollateralToDebtRatio(ctx, cdp.Collateral, cdp.Principal.Add(cdp.AccumulatedFees...))\n\tk.SetCdpAndCollateralRatioIndex(ctx, cdp, collateralToDebtRatio)\n\treturn nil\n}", "func (_TokensNetwork *TokensNetworkTransactor) UpdateBalanceProof(opts *bind.TransactOpts, token common.Address, partner common.Address, transferred_amount *big.Int, locksroot [32]byte, nonce uint64, additional_hash [32]byte, partner_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.contract.Transact(opts, \"updateBalanceProof\", token, partner, transferred_amount, locksroot, nonce, additional_hash, partner_signature)\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 DeployDelegationController(auth *bind.TransactOpts, backend bind.ContractBackend) (common.Address, *types.Transaction, *DelegationController, error) {\n\tparsed, err := abi.JSON(strings.NewReader(DelegationControllerABI))\n\tif err != nil {\n\t\treturn common.Address{}, nil, nil, err\n\t}\n\n\taddress, tx, contract, err := bind.DeployContract(auth, parsed, common.FromHex(DelegationControllerBin), backend)\n\tif err != nil {\n\t\treturn common.Address{}, nil, nil, err\n\t}\n\treturn address, tx, &DelegationController{DelegationControllerCaller: DelegationControllerCaller{contract: contract}, DelegationControllerTransactor: DelegationControllerTransactor{contract: contract}, DelegationControllerFilterer: DelegationControllerFilterer{contract: contract}}, nil\n}", "func (va ClawbackVestingAccount) distributeReward(ctx sdk.Context, ak AccountKeeper, bondDenom string, reward sdk.Coins) {\n\tnow := ctx.BlockTime().Unix()\n\tt := va.StartTime\n\tfirstUnvestedPeriod := 0\n\tunvestedTokens := sdk.ZeroInt()\n\tfor i, period := range va.VestingPeriods {\n\t\tt += period.Length\n\t\tif t <= now {\n\t\t\tfirstUnvestedPeriod = i + 1\n\t\t\tcontinue\n\t\t}\n\t\tunvestedTokens = unvestedTokens.Add(period.Amount.AmountOf(bondDenom))\n\t}\n\n\trunningTotReward := sdk.NewCoins()\n\trunningTotStaking := sdk.ZeroInt()\n\tfor i := firstUnvestedPeriod; i < len(va.VestingPeriods); i++ {\n\t\tperiod := va.VestingPeriods[i]\n\t\trunningTotStaking = runningTotStaking.Add(period.Amount.AmountOf(bondDenom))\n\t\trunningTotRatio := runningTotStaking.ToDec().Quo(unvestedTokens.ToDec())\n\t\ttargetCoins := scaleCoins(reward, runningTotRatio)\n\t\tthisReward := targetCoins.Sub(runningTotReward)\n\t\trunningTotReward = targetCoins\n\t\tperiod.Amount = period.Amount.Add(thisReward...)\n\t\tva.VestingPeriods[i] = period\n\t}\n\n\tva.OriginalVesting = va.OriginalVesting.Add(reward...)\n\tak.SetAccount(ctx, &va)\n}", "func (k Keeper) RepayPrincipal(ctx sdk.Context, owner sdk.AccAddress, collateralType string, payment sdk.Coin) error {\n\t// validation\n\tcdp, found := k.GetCdpByOwnerAndCollateralType(ctx, owner, collateralType)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrCdpNotFound, \"owner %s, denom %s\", owner, collateralType)\n\t}\n\n\terr := k.ValidatePaymentCoins(ctx, cdp, payment)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = k.ValidateBalance(ctx, payment, owner)\n\tif err != nil {\n\t\treturn err\n\t}\n\tk.hooks.BeforeCDPModified(ctx, cdp)\n\tcdp = k.SynchronizeInterest(ctx, cdp)\n\n\t// Note: assumes cdp.Principal and cdp.AccumulatedFees don't change during calculations\n\ttotalPrincipal := cdp.GetTotalPrincipal()\n\n\t// calculate fee and principal payment\n\tfeePayment, principalPayment := k.calculatePayment(ctx, totalPrincipal, cdp.AccumulatedFees, payment)\n\n\terr = k.validatePrincipalPayment(ctx, cdp, principalPayment)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// send the payment from the sender to the cpd module\n\terr = k.bankKeeper.SendCoinsFromAccountToModule(ctx, owner, types.ModuleName, sdk.NewCoins(feePayment.Add(principalPayment)))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// burn the payment coins\n\terr = k.bankKeeper.BurnCoins(ctx, types.ModuleName, sdk.NewCoins(feePayment.Add(principalPayment)))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// burn the corresponding amount of debt coins\n\tcdpDebt := k.getModAccountDebt(ctx, types.ModuleName)\n\tpaymentAmount := feePayment.Add(principalPayment).Amount\n\n\tdebtDenom := k.GetDebtDenom(ctx)\n\tcoinsToBurn := sdk.NewCoin(debtDenom, paymentAmount)\n\n\tif paymentAmount.GT(cdpDebt) {\n\t\tcoinsToBurn = sdk.NewCoin(debtDenom, cdpDebt)\n\t}\n\n\terr = k.BurnDebtCoins(ctx, types.ModuleName, debtDenom, coinsToBurn)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// emit repayment event\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeCdpRepay,\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, feePayment.Add(principalPayment).String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyCdpID, fmt.Sprintf(\"%d\", cdp.ID)),\n\t\t),\n\t)\n\n\t// remove the old collateral:debt ratio index\n\n\t// update cdp state\n\tif !principalPayment.IsZero() {\n\t\tcdp.Principal = cdp.Principal.Sub(principalPayment)\n\t}\n\tcdp.AccumulatedFees = cdp.AccumulatedFees.Sub(feePayment)\n\n\t// decrement the total principal for the input collateral type\n\tk.DecrementTotalPrincipal(ctx, cdp.Type, feePayment.Add(principalPayment))\n\n\t// if the debt is fully paid, return collateral to depositors,\n\t// and remove the cdp and indexes from the store\n\tif cdp.Principal.IsZero() && cdp.AccumulatedFees.IsZero() {\n\t\tk.ReturnCollateral(ctx, cdp)\n\t\tk.RemoveCdpOwnerIndex(ctx, cdp)\n\t\terr := k.DeleteCdpAndCollateralRatioIndex(ctx, cdp)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// emit cdp close event\n\t\tctx.EventManager().EmitEvent(\n\t\t\tsdk.NewEvent(\n\t\t\t\ttypes.EventTypeCdpClose,\n\t\t\t\tsdk.NewAttribute(types.AttributeKeyCdpID, fmt.Sprintf(\"%d\", cdp.ID)),\n\t\t\t),\n\t\t)\n\t\treturn nil\n\t}\n\n\t// set cdp state and update indexes\n\tcollateralToDebtRatio := k.CalculateCollateralToDebtRatio(ctx, cdp.Collateral, cdp.Type, cdp.GetTotalPrincipal())\n\treturn k.UpdateCdpAndCollateralRatioIndex(ctx, cdp, collateralToDebtRatio)\n}", "func (theAccount *Account) Deposit(amount int) {\n\ttheAccount.balance += amount\n}", "func (_DelegationController *DelegationControllerSession) GetAndUpdateForbiddenForDelegationAmount(wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateForbiddenForDelegationAmount(&_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 (bva BaseVestingAccount) GetDelegatedFree() sdk.Coins {\n\treturn bva.DelegatedFree\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 calculateRewards(delegationTotal loom.BigUInt, params *Params, totalValidatorDelegations loom.BigUInt) loom.BigUInt {\n\tcycleSeconds := params.ElectionCycleLength\n\treward := CalculateFraction(blockRewardPercentage, delegationTotal)\n\n\t// If totalValidator Delegations are high enough to make simple reward\n\t// calculations result in more rewards given out than the value of `MaxYearlyReward`,\n\t// scale the rewards appropriately\n\tyearlyRewardTotal := CalculateFraction(blockRewardPercentage, totalValidatorDelegations)\n\tif yearlyRewardTotal.Cmp(&params.MaxYearlyReward.Value) > 0 {\n\t\treward.Mul(&reward, &params.MaxYearlyReward.Value)\n\t\treward.Div(&reward, &yearlyRewardTotal)\n\t}\n\n\t// When election cycle = 0, estimate block time at 2 sec\n\tif cycleSeconds == 0 {\n\t\tcycleSeconds = 2\n\t}\n\treward.Mul(&reward, &loom.BigUInt{big.NewInt(cycleSeconds)})\n\treward.Div(&reward, &secondsInYear)\n\n\treturn reward\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 (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 (_CrToken *CrTokenTransactor) RepayBorrowBehalf(opts *bind.TransactOpts, borrower common.Address, repayAmount *big.Int) (*types.Transaction, error) {\n\treturn _CrToken.contract.Transact(opts, \"repayBorrowBehalf\", borrower, repayAmount)\n}", "func (account *Account) Deposit(amount int) {\r\n\taccount.balance += amount\r\n}", "func (_TokensNetwork *TokensNetworkTransactorSession) UpdateBalanceProof(token common.Address, partner common.Address, transferred_amount *big.Int, locksroot [32]byte, nonce uint64, additional_hash [32]byte, partner_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.UpdateBalanceProof(&_TokensNetwork.TransactOpts, token, partner, transferred_amount, locksroot, nonce, additional_hash, partner_signature)\n}", "func (_DelegationController *DelegationControllerTransactorSession) GetAndUpdateForbiddenForDelegationAmount(wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateForbiddenForDelegationAmount(&_DelegationController.TransactOpts, wallet)\n}", "func (del Delegation) UnlockPenalty(args struct{ Amount hexutil.Big }) (hexutil.Big, error) {\n\treturn repository.R().DelegationUnlockPenalty(&del.Address, (*big.Int)(del.Delegation.ToStakerId), (*big.Int)(&args.Amount))\n}", "func (_CrToken *CrTokenSession) RepayBorrowBehalf(borrower common.Address, repayAmount *big.Int) (*types.Transaction, error) {\n\treturn _CrToken.Contract.RepayBorrowBehalf(&_CrToken.TransactOpts, borrower, repayAmount)\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 (_Bindings *BindingsTransactor) RepayBorrowBehalf(opts *bind.TransactOpts, borrower common.Address) (*types.Transaction, error) {\n\treturn _Bindings.contract.Transact(opts, \"repayBorrowBehalf\", borrower)\n}", "func (_Caller *CallerTransactor) WithdrawFees(opts *bind.TransactOpts, to common.Address) (*types.Transaction, error) {\n\treturn _Caller.contract.Transact(opts, \"withdrawFees\", to)\n}", "func (_DelegationController *DelegationControllerTransactor) GetAndUpdateEffectiveDelegatedByHolderToValidator(opts *bind.TransactOpts, holder common.Address, validatorId *big.Int, month *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"getAndUpdateEffectiveDelegatedByHolderToValidator\", holder, validatorId, month)\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 *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 (_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 (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 (c *Client) PropagateBalance(\n\tctx context.Context,\n\tid string,\n\tmint string,\n) (*BalanceResource, error) {\n\treq, err := http.NewRequest(\"POST\",\n\t\tFullMintURL(ctx, mint,\n\t\t\tfmt.Sprintf(\"/balances/%s\", id), url.Values{}).String(), nil)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\treq.Header.Add(\"Mint-Protocol-Version\", ProtocolVersion)\n\tr, err := c.httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\tdefer r.Body.Close()\n\n\tvar raw svc.Resp\n\tif err := json.NewDecoder(r.Body).Decode(&raw); err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\tif r.StatusCode != http.StatusOK && r.StatusCode != http.StatusCreated {\n\t\tvar e errors.ConcreteUserError\n\t\terr = raw.Extract(\"error\", &e)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\treturn nil, errors.Trace(ErrMintClient{\n\t\t\tr.StatusCode, e.ErrCode, e.ErrMessage,\n\t\t})\n\t}\n\n\tvar balance BalanceResource\n\tif err := raw.Extract(\"balance\", &balance); err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\treturn &balance, nil\n}", "func (a *Account) Deposit (amount int) {\n\ta.balance += amount\n}", "func (k Keeper) SetWithdrawAddr(ctx sdk.Context, delegatorId chainTypes.AccountID, withdrawId chainTypes.AccountID) error {\n\tif k.blacklistedAddrs[withdrawId.String()] {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, \"%s is blacklisted from receiving external funds\", withdrawId)\n\t}\n\n\tif !k.GetWithdrawAddrEnabled(ctx) {\n\t\treturn types.ErrSetWithdrawAddrDisabled\n\t}\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeSetWithdrawAddress,\n\t\t\tsdk.NewAttribute(types.AttributeKeyWithdrawAddress, withdrawId.String()),\n\t\t),\n\t)\n\n\tk.SetDelegatorWithdrawAddr(ctx, delegatorId, withdrawId)\n\treturn nil\n}", "func (s *State) AdvanceUpdate(ua UpdateAdvancement) (err error) {\n\tw, err := s.LoadWallet(ua.WalletID)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor i := range w.Sector.ActiveUpdates {\n\t\tif w.Sector.ActiveUpdates[i].Event.UpdateIndex == ua.UpdateIndex {\n\t\t\tw.Sector.ActiveUpdates[i].Confirmations[ua.SiblingIndex] = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\terr = s.SaveWallet(w)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (a *Account) Deposit(amount int) {\n\ta.balance += amount\n}" ]
[ "0.63843423", "0.6348469", "0.63280714", "0.6127292", "0.6099896", "0.59851784", "0.5903084", "0.5901659", "0.58393365", "0.57900774", "0.5761572", "0.5679458", "0.5625733", "0.562472", "0.55934227", "0.5562052", "0.55510765", "0.5547109", "0.55152845", "0.55124575", "0.5427714", "0.53968793", "0.5304026", "0.529983", "0.5286176", "0.5281452", "0.5228556", "0.5206727", "0.5188", "0.51672626", "0.5164376", "0.5146589", "0.51269794", "0.5070188", "0.50552267", "0.5046415", "0.5042505", "0.5038563", "0.5010161", "0.49685147", "0.49684387", "0.49561948", "0.49232695", "0.4907573", "0.4905251", "0.49020055", "0.48969635", "0.4892147", "0.48862943", "0.487867", "0.4849024", "0.48318028", "0.48290014", "0.4828362", "0.4806713", "0.48037153", "0.480348", "0.47881603", "0.47571716", "0.47515076", "0.47296995", "0.4724797", "0.47204968", "0.47176188", "0.47148028", "0.47049314", "0.46647286", "0.46538943", "0.46441612", "0.46438286", "0.46375227", "0.46301252", "0.46250084", "0.4619643", "0.4614884", "0.4612812", "0.46021104", "0.45953768", "0.45928022", "0.45914862", "0.45818037", "0.45769206", "0.45756292", "0.45722038", "0.45695314", "0.45660195", "0.45551983", "0.45551953", "0.45551834", "0.4554903", "0.45540223", "0.45500895", "0.45451683", "0.4531914", "0.4516473", "0.45037776", "0.44993067", "0.44921425", "0.44859782", "0.4483" ]
0.8535179
0
NewClawbackAction returns an exported.ClawbackAction for ClawbackVestingAccount.
NewClawbackAction возвращает экспортированный ClawbackAction для ClawbackVestingAccount.
func NewClawbackAction(requestor, dest sdk.AccAddress, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) exported.ClawbackAction { return clawbackAction{ requestor: requestor, dest: dest, ak: ak, bk: bk, sk: sk, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "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 NewClawbackRewardAction(ak AccountKeeper, bk BankKeeper, sk StakingKeeper) exported.RewardAction {\n\treturn clawbackRewardAction{\n\t\tak: ak,\n\t\tbk: bk,\n\t\tsk: sk,\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 NewCollateralizeAction(c *Collateralize, tx *types.Transaction, index int) *Action {\n\thash := tx.Hash()\n\tfromaddr := tx.From()\n\tcfg := c.GetAPI().GetConfig()\n\ttokenDb, err := account.NewAccountDB(cfg, tokenE.GetName(), pty.CCNYTokenName, c.GetStateDB())\n\tif err != nil {\n\t\tclog.Error(\"NewCollateralizeAction\", \"Get Account DB error\", \"error\", err)\n\t\treturn nil\n\t}\n\n\treturn &Action{\n\t\tcoinsAccount: c.GetCoinsAccount(), tokenAccount: tokenDb, db: c.GetStateDB(), localDB: c.GetLocalDB(),\n\t\ttxhash: hash, fromaddr: fromaddr, blocktime: c.GetBlockTime(), height: c.GetHeight(),\n\t\texecaddr: dapp.ExecAddress(string(tx.Execer)), difficulty: c.GetDifficulty(), index: index, Collateralize: c}\n}", "func (va *ClawbackVestingAccount) clawback(ctx sdk.Context, dest sdk.AccAddress, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) error {\n\t// Compute the clawback based on the account state only, and update account\n\ttoClawBack := va.computeClawback(ctx.BlockTime().Unix())\n\tif toClawBack.IsZero() {\n\t\treturn nil\n\t}\n\taddr := va.GetAddress()\n\tbondDenom := sk.BondDenom(ctx)\n\n\t// Compute the clawback based on bank balance and delegation, and update account\n\tencumbered := va.GetVestingCoins(ctx.BlockTime())\n\tbondedAmt := sk.GetDelegatorBonded(ctx, addr)\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, addr)\n\tbonded := sdk.NewCoins(sdk.NewCoin(bondDenom, bondedAmt))\n\tunbonding := sdk.NewCoins(sdk.NewCoin(bondDenom, unbondingAmt))\n\tunbonded := bk.GetAllBalances(ctx, addr)\n\ttoClawBack = va.updateDelegation(encumbered, toClawBack, bonded, unbonding, unbonded)\n\n\t// Write now now so that the bank module sees unvested tokens are unlocked.\n\t// Note that all store writes are aborted if there is a panic, so there is\n\t// no danger in writing incomplete results.\n\tak.SetAccount(ctx, va)\n\n\t// Now that future vesting events (and associated lockup) are removed,\n\t// the balance of the account is unlocked and can be freely transferred.\n\tspendable := bk.SpendableCoins(ctx, addr)\n\ttoXfer := coinsMin(toClawBack, spendable)\n\terr := bk.SendCoins(ctx, addr, dest, toXfer)\n\tif err != nil {\n\t\treturn err // shouldn't happen, given spendable check\n\t}\n\ttoClawBack = toClawBack.Sub(toXfer)\n\n\t// We need to traverse the staking data structures to update the\n\t// vesting account bookkeeping, and to recover more funds if necessary.\n\t// Staking is the only way unvested tokens should be missing from the bank balance.\n\n\t// If we need more, transfer UnbondingDelegations.\n\twant := toClawBack.AmountOf(bondDenom)\n\tunbondings := sk.GetUnbondingDelegations(ctx, addr, math.MaxUint16)\n\tfor _, unbonding := range unbondings {\n\t\tvalAddr, err := sdk.ValAddressFromBech32(unbonding.ValidatorAddress)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\ttransferred := sk.TransferUnbonding(ctx, addr, dest, valAddr, want)\n\t\twant = want.Sub(transferred)\n\t\tif !want.IsPositive() {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// If we need more, transfer Delegations.\n\tif want.IsPositive() {\n\t\tdelegations := sk.GetDelegatorDelegations(ctx, addr, math.MaxUint16)\n\t\tfor _, delegation := range delegations {\n\t\t\tvalidatorAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err) // shouldn't happen\n\t\t\t}\n\t\t\tvalidator, found := sk.GetValidator(ctx, validatorAddr)\n\t\t\tif !found {\n\t\t\t\t// validator has been removed\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\twantShares, err := validator.SharesFromTokensTruncated(want)\n\t\t\tif err != nil {\n\t\t\t\t// validator has no tokens\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttransferredShares := sk.TransferDelegation(ctx, addr, dest, delegation.GetValidatorAddr(), wantShares)\n\t\t\t// to be conservative in what we're clawing back, round transferred shares up\n\t\t\ttransferred := validator.TokensFromSharesRoundUp(transferredShares).RoundInt()\n\t\t\twant = want.Sub(transferred)\n\t\t\tif !want.IsPositive() {\n\t\t\t\t// Could be slightly negative, due to rounding?\n\t\t\t\t// Don't think so, due to the precautions above.\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// If we've transferred everything and still haven't transferred the desired clawback amount,\n\t// then the account must have most some unvested tokens from slashing.\n\treturn nil\n}", "func NewBcBotAction(j *bot.Jobs) *BcBotAction {\n\t// client := resty.New()\n\t// client.\n\t// \tSetRetryCount(3).\n\t// \tSetRetryWaitTime(10 * time.Second)\n\treturn &BcBotAction{jobs: j, client: nil, mutex: new(sync.RWMutex)}\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 (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 NewRecoverableAction(supervisor *Supervisor) *RecoverableAction {\n\tra := &RecoverableAction{\n\t\tactionChan: make(chan Action),\n\t\treplyChan: make(chan string, 5),\n\t\tsupervisor: supervisor,\n\t}\n\n\tra.heartbeat = NewHeartbeat(ra, 1e8)\n\n\tgo ra.backend()\n\n\treturn ra\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 CreateAction(action func(*cli.Context) error) func(*cli.Context) error {\n\treturn func(c *cli.Context) error {\n\t\terr := action(c)\n\t\tif err != nil {\n\t\t\tiocli.Error(\"%s\", err)\n\t\t}\n\n\t\treturn nil\n\t}\n}", "func NewCheck() beekeeper.Action {\n\treturn &Check{}\n}", "func NewAction(app *buffalo.App) *Action {\n\tas := &Action{\n\t\tApp: app,\n\t\tModel: NewModel(),\n\t}\n\treturn as\n}", "func New() Action {\n\treturn &action{}\n}", "func NewAction(name string, arg interface{}) {\n\tDefaultActionRegistry.Post(name, arg)\n}", "func NewRollbackAction(kit kit.Kit, viper *viper.Viper,\n\tauthSvrCli pbauthserver.AuthClient, dataMgrCli pbdatamanager.DataManagerClient,\n\tgseControllerCli pbgsecontroller.GSEControllerClient,\n\treq *pb.RollbackReleaseReq, resp *pb.RollbackReleaseResp) *RollbackAction {\n\n\taction := &RollbackAction{\n\t\tkit: kit,\n\t\tviper: viper,\n\t\tauthSvrCli: authSvrCli,\n\t\tdataMgrCli: dataMgrCli,\n\t\tgseControllerCli: gseControllerCli,\n\t\treq: req,\n\t\tresp: resp,\n\t}\n\n\taction.resp.Result = true\n\taction.resp.Code = pbcommon.ErrCode_E_OK\n\taction.resp.Message = \"OK\"\n\n\treturn action\n}", "func NewChallengeAction(msg *Message) (*ChallengeAction, error) {\n\taction := &ChallengeAction{*msg}\n\n\treturn action, nil\n}", "func NewAction(t *Pos33Ticket, tx *types.Transaction) *Action {\n\thash := tx.Hash()\n\tfromaddr := tx.From()\n\treturn &Action{t.GetCoinsAccount(), t.GetStateDB(), hash, fromaddr,\n\t\tt.GetBlockTime(), t.GetHeight(), dapp.ExecAddress(string(tx.Execer)), t.GetAPI()}\n}", "func NewAction(payload interface{}) Action {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Error: %v\\n\", r)\n\t\t\tfmt.Fprintf(os.Stderr, \"Payload: %v\\n\", payload)\n\t\t}\n\t}()\n\n\tvar a Action\n\ta.payload = payload\n\ta.headers = make(map[string]string)\n\n\tfor k, v := range payload.(map[interface{}]interface{}) {\n\t\tswitch k {\n\t\tcase \"catch\":\n\t\t\ta.catch = v.(string)\n\t\tcase \"warnings\":\n\t\t\t// TODO\n\t\t\tcontinue\n\t\tcase \"allowed_warnings\":\n\t\t\t// TODO\n\t\t\tcontinue\n\t\tcase \"node_selector\":\n\t\t\tcontinue\n\t\tcase \"headers\":\n\t\t\tfor kk, vv := range v.(map[interface{}]interface{}) {\n\t\t\t\ta.headers[kk.(string)] = vv.(string)\n\t\t\t}\n\t\tdefault:\n\t\t\ta.method = k.(string)\n\t\t\ta.params = v.(map[interface{}]interface{})\n\t\t}\n\t}\n\n\treturn a\n}", "func CreateAction(\n\tcmd, keyB, id, secretKey string,\n\targs ...interface{}) *types.Action {\n\n\tmac := hmac.New(sha1.New, []byte(secretKey))\n\tmac.Write([]byte(cmd))\n\tmac.Write([]byte(keyB))\n\tmac.Write([]byte(id))\n\tsum := mac.Sum(nil)\n\tsumhex := hex.EncodeToString(sum)\n\n\treturn &types.Action{\n\t\tCommand: cmd,\n\t\tStorageKey: keyB,\n\t\tArgs: args,\n\t\tId: id,\n\t\tSecret: sumhex,\n\t}\n}", "func NewAction() actions.Action {\n\treturn &Action{}\n}", "func NewAction() actions.Action {\n\treturn &Action{}\n}", "func NewAction() actions.Action {\n\treturn &action{}\n}", "func NewRecvAction(args any) *Action {\n\treturn &Action{Args: args}\n}", "func New() *Action {\n\treturn &Action{}\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 NewCheckmate(winner Colour) Outcome { return Outcome{Winner: winner, Reason: checkmate} }", "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 NewAuthorizeAction(ctx context.Context, viper *viper.Viper, authMode string,\n\tlocalAuthController *local.Controller, bkiamAuthController *bkiam.Controller,\n\treq *pb.AuthorizeReq, resp *pb.AuthorizeResp) *AuthorizeAction {\n\n\taction := &AuthorizeAction{\n\t\tctx: ctx,\n\t\tviper: viper,\n\t\tauthMode: authMode,\n\t\tlocalAuthController: localAuthController,\n\t\tbkiamAuthController: bkiamAuthController,\n\t\treq: req,\n\t\tresp: resp,\n\t}\n\n\taction.resp.Seq = req.Seq\n\taction.resp.Code = pbcommon.ErrCode_E_OK\n\taction.resp.Message = \"OK\"\n\n\treturn action\n}", "func New() *Action {\n\treturn &Action{w: os.Stdout}\n}", "func CreateAction(r *Raptor) *Action {\n\treturn &Action{\n\t\tRaptor: r,\n\t}\n}", "func NewAction(cmd Command) Action {\n\tswitch cmd.name {\n\tcase buildCommand:\n\t\treturn NewBuildAction(afero.NewOsFs(), cmd.helmRepoName, cmd.artifactsPath)\n\tdefault:\n\t\treturn ShowAction{}\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 NewAction(fn ActionFn) *Action {\n\treturn &Action{\n\t\tfn: fn,\n\t\tdoneCh: make(chan struct{}),\n\t}\n}", "func NewCreateAction(model store.ClusterManagerModel) *CreateAction {\n\treturn &CreateAction{\n\t\tmodel: model,\n\t}\n}", "func NewAction(conf config.Server) Action {\n\treturn Action{\n\t\ttcp: tcp.NewService(conf),\n\t\tudp: udp.NewService(conf),\n\t}\n}", "func NewEvictAction() Action {\n\treturn &evictAction{}\n}", "func New() *Clac {\n\tc := &Clac{keepHist: true}\n\tc.Reset()\n\treturn c\n}", "func (act *ActionTrace) Action() (*ActionTrace, error) {\n\treturn act, nil\n}", "func (t tSessions) newC(w http.ResponseWriter, r *http.Request, ctr, act string) *contr.Sessions {\n\t// Allocate a new controller. Set values of special fields, if necessary.\n\tc := &contr.Sessions{\n\n\t\tRequest: r,\n\n\t\tResponse: w,\n\t}\n\n\treturn c\n}", "func NewCreateAction(kit kit.Kit, viper *viper.Viper,\n\tauthSvrCli pbauthserver.AuthClient, dataMgrCli pbdatamanager.DataManagerClient,\n\treq *pb.CreateStrategyReq, resp *pb.CreateStrategyResp) *CreateAction {\n\n\taction := &CreateAction{\n\t\tkit: kit,\n\t\tviper: viper,\n\t\tauthSvrCli: authSvrCli,\n\t\tdataMgrCli: dataMgrCli,\n\t\treq: req,\n\t\tresp: resp,\n\t}\n\n\taction.resp.Result = true\n\taction.resp.Code = pbcommon.ErrCode_E_OK\n\taction.resp.Message = \"OK\"\n\n\taction.labelsOr = []map[string]string{}\n\taction.labelsAnd = []map[string]string{}\n\n\treturn action\n}", "func NewCreateAction(model store.ClusterManagerModel, k8sop *clusterops.K8SOperator) *CreateAction {\n\treturn &CreateAction{\n\t\tmodel: model,\n\t\tk8sop: k8sop,\n\t}\n}", "func NewLabelActionBase()(*LabelActionBase) {\n m := &LabelActionBase{\n }\n m.backingStore = ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStoreFactoryInstance();\n m.SetAdditionalData(make(map[string]any))\n return m\n}", "func NewCreateAction(viper *viper.Viper, dataMgrCli pbdatamanager.DataManagerClient,\n\treq *pb.CreateAppReq, resp *pb.CreateAppResp) *CreateAction {\n\taction := &CreateAction{viper: viper, dataMgrCli: dataMgrCli, req: req, resp: resp}\n\n\taction.resp.Seq = req.Seq\n\taction.resp.ErrCode = pbcommon.ErrCode_E_OK\n\taction.resp.ErrMsg = \"OK\"\n\n\treturn action\n}", "func CreateUserAction(context *web.AppContext) *web.AppError {\n\n\tdb := context.MDB\n\tvar input model.CayUserAction\n\tjson.NewDecoder(context.Body).Decode(&input)\n\n\tinput.ID = bson.NewObjectId()\n\tinput.Date = time.Now()\n\tif input.Release == \"\" {\n\t\tinput.Release = \"0.1.0\"\n\t}\n\terr := db.DB.C(model.CayUserActions).Insert(input)\n\tif err != nil {\n\t\tmessage := fmt.Sprintf(\"Error creating user-action [%s]\", err)\n\t\treturn &web.AppError{err, message, http.StatusInternalServerError}\n\t}\n\n\treturn nil\n}", "func CiActionInstall(parent interface{}) error {\n\tthis := parent.(*ActionSaver)\n\tthis.SetParam(\"success\", \"ciserver\")\n\terr, _, _, _ := executeCommand(makeArgsFromString(\"systemctl enable citool\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\tthis.SetParam(\"success\", \"ciserver_en\")\n\n\tdata0, err := data.Asset(\"cisetup/src/data/sudoers\")\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(\"/etc/sudoers\", data0, 0440)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr, _, _, _ = executeCommand(makeArgsFromString(\"setcap cap_sys_chroot+ep /usr/sbin/chroot\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr, _, _, _ = executeCommand(makeArgsFromString(\"setcap cap_sys_chroot+ep /usr/sbin/citool\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdata2_2_tmp, err := data.Asset(\"cisetup/src/data/citool.ini\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdata2_2 := replace_string(data2_2_tmp, \"sonarPASSSWD\", db_passwd)\n\terr = ioutil.WriteFile(\"/etc/citool.ini\", data2_2, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr, _, _, _ = executeCommand(makeArgsFromString(\"systemctl start citool\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr, _, _, _ = executeCommand(makeArgsFromString(\"/usr/bin/chown checker:checker /etc/citool.ini\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\tthis.SetParam(\"success\", \"ciserver_st\")\n\n\tdata3_3, err := data.Asset(\"cisetup/src/data/config\")\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(\"/root/config\", data3_3, 0400)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Create(\n\tcontext contexts.Contextable,\n\tlogger *logger.Logger,\n\tconnection *golastic.Connection,\n\tqueue *notifications.Queue,\n\tctx context.Context,\n) (Actionable, error) {\n\taction, err := build(context.Action())\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := action.Init(context, logger, connection, queue, ctx); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := action.ApplyOptions().ApplyFilters(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn action, nil\n}", "func (ca clawbackAction) TakeFromAccount(ctx sdk.Context, rawAccount exported.VestingAccount) error {\n\tcva, ok := rawAccount.(*ClawbackVestingAccount)\n\tif !ok {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrNotSupported, \"clawback expects *ClawbackVestingAccount, got %T\", rawAccount)\n\t}\n\tif ca.requestor.String() != cva.FunderAddress {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, \"clawback can only be requested by original funder %s\", cva.FunderAddress)\n\t}\n\treturn cva.clawback(ctx, ca.dest, ca.ak, ca.bk, ca.sk)\n}", "func newKubeadmConfigAction() Action {\n\treturn &kubeadmConfigAction{}\n}", "func (e *ExpectedClusterSetup) WithAction(action interface{}) *ExpectedClusterSetup {\n\te.arg0 = action\n\treturn e\n}", "func CreateBackupAction(service *pgCommon.PostgresServiceInformations) action.IAction {\n\treturn action.FormAction{\n\t\tName: \"Backup\",\n\t\tUniqueCommand: \"cmd_pg_create_backup\",\n\t\tPlaceholder: nil,\n\t\tActionExecuteCallback: func(placeholder interface{}) (interface{}, error) {\n\t\t\treturn nil, CreateBackup(service)\n\t\t},\n\t}\n}", "func (t tApp) newC(w http.ResponseWriter, r *http.Request, ctr, act string) *contr.App {\n\t// Allocate a new controller. Set values of special fields, if necessary.\n\tc := &contr.App{}\n\n\t// Allocate its parents. Make sure controller of every type\n\t// is allocated just once, then reused.\n\tc.Controllers = &contr.Controllers{}\n\tc.Controllers.Templates = c.Controllers.Errors.Templates\n\tc.Controllers.Errors = &c5.Errors{}\n\tc.Controllers.Static = &c3.Static{}\n\tc.Controllers.Sessions = &c2.Sessions{\n\n\t\tRequest: r,\n\n\t\tResponse: w,\n\t}\n\tc.Controllers.Requests = &c1.Requests{\n\n\t\tRequest: r,\n\n\t\tResponse: w,\n\t}\n\tc.Controllers.Global = &c0.Global{\n\n\t\tCurrentAction: act,\n\n\t\tCurrentController: ctr,\n\t}\n\tc.Controllers.Errors.Templates = &c4.Templates{}\n\tc.Controllers.Errors.Templates.Requests = c.Controllers.Requests\n\tc.Controllers.Errors.Templates.Global = c.Controllers.Global\n\tc.Controllers.Templates.Requests = c.Controllers.Requests\n\tc.Controllers.Templates.Global = c.Controllers.Global\n\n\treturn c\n}", "func NewActions(a ...Action) {\n\tDefaultActionRegistry.PostBatch(a...)\n}", "func NewAction(name string) *Action {\n\ta := &Action{\n\t\tName: name,\n\t\tEnabled: true,\n\t}\n\treturn a\n}", "func NewGetAction(model store.ClusterManagerModel) *GetAction {\n\treturn &GetAction{\n\t\tmodel: model,\n\t}\n}", "func GetAction(client *whisk.Client, actionName string) func() (*whisk.Action, error) {\n\treturn func() (*whisk.Action, error) {\n\t\taction, _, err := client.Actions.Get(actionName, true)\n\t\tif err == nil {\n\t\t\treturn action, nil\n\t\t}\n\t\treturn nil, err\n\t}\n}", "func NewWebhook() *NamespaceWebhook {\n\tscheme := runtime.NewScheme()\n\terr := admissionv1.AddToScheme(scheme)\n\tif err != nil {\n\t\tlog.Error(err, \"Fail adding admissionsv1 scheme to NamespaceWebhook\")\n\t\tos.Exit(1)\n\t}\n\n\terr = corev1.AddToScheme(scheme)\n\tif err != nil {\n\t\tlog.Error(err, \"Fail adding corev1 scheme to NamespaceWebhook\")\n\t\tos.Exit(1)\n\t}\n\n\treturn &NamespaceWebhook{\n\t\ts: *scheme,\n\t}\n}", "func newClaBuilder(clusterName string, dropPercents []uint32) *claBuilder {\n\tvar drops []*v3endpointpb.ClusterLoadAssignment_Policy_DropOverload\n\tfor i, d := range dropPercents {\n\t\tdrops = append(drops, &v3endpointpb.ClusterLoadAssignment_Policy_DropOverload{\n\t\t\tCategory: fmt.Sprintf(\"test-drop-%d\", i),\n\t\t\tDropPercentage: &v3typepb.FractionalPercent{\n\t\t\t\tNumerator: d,\n\t\t\t\tDenominator: v3typepb.FractionalPercent_HUNDRED,\n\t\t\t},\n\t\t})\n\t}\n\n\treturn &claBuilder{\n\t\tv: &v3endpointpb.ClusterLoadAssignment{\n\t\t\tClusterName: clusterName,\n\t\t\tPolicy: &v3endpointpb.ClusterLoadAssignment_Policy{\n\t\t\t\tDropOverloads: drops,\n\t\t\t},\n\t\t},\n\t}\n}", "func NewListAction(model store.ClusterManagerModel) *ListAction {\n\treturn &ListAction{\n\t\tmodel: model,\n\t}\n}", "func FactoryAction(factory CommandFactory, log logging.Logger, cmdName string) func(*cli.Context) {\n\treturn func(c *cli.Context) {\n\t\tcmd := factory(c, log, cmdName)\n\t\texit, err := cmd.Run()\n\n\t\t// For API reasons, we may return an error but a zero exit code. So we want\n\t\t// to check and log both.\n\t\tif exit != 0 || err != nil {\n\t\t\tlog.Error(\n\t\t\t\t\"Command encountered error. command:%s, exit:%d, err:%s\",\n\t\t\t\tcmdName, exit, err,\n\t\t\t)\n\t\t}\n\n\t\tos.Exit(exit)\n\t}\n}", "func (m *Client) CreateWebhook(arg0 context.Context, arg1 *zendesk.Webhook) (*zendesk.Webhook, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateWebhook\", arg0, arg1)\n\tret0, _ := ret[0].(*zendesk.Webhook)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func NewActionResultPart()(*ActionResultPart) {\n m := &ActionResultPart{\n }\n m.SetAdditionalData(make(map[string]interface{}));\n return m\n}", "func NewWatcherAction() *WatcherAction {\n\tr := &WatcherAction{}\n\n\treturn r\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 NewAccessControl(address common.Address, backend bind.ContractBackend) (*AccessControl, error) {\n\tcontract, err := bindAccessControl(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &AccessControl{AccessControlCaller: AccessControlCaller{contract: contract}, AccessControlTransactor: AccessControlTransactor{contract: contract}, AccessControlFilterer: AccessControlFilterer{contract: contract}}, nil\n}", "func NewAccessControl(address common.Address, backend bind.ContractBackend) (*AccessControl, error) {\n\tcontract, err := bindAccessControl(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &AccessControl{AccessControlCaller: AccessControlCaller{contract: contract}, AccessControlTransactor: AccessControlTransactor{contract: contract}, AccessControlFilterer: AccessControlFilterer{contract: contract}}, nil\n}", "func NewAction(action EngineAction) *PacketUnstable {\n\tpkt := &PacketUnstable{}\n\tswitch action := action.(type) {\n\tcase ButtonPressedAction:\n\t\tpkt.Cmd = CmdButtonPressedAction\n\tcase ButtonReleasedAction:\n\t\tpkt.Cmd = CmdButtonReleasedAction\n\tdefault:\n\t\tpanic(fmt.Errorf(\"support for action %T not yet implemented\", action))\n\t}\n\tbuf := &bytes.Buffer{}\n\tif err := binary.Write(buf, binary.LittleEndian, action); err != nil {\n\t\tdie(err)\n\t}\n\tpkt.Data = buf.Bytes()\n\treturn pkt\n}", "func NewListAction(model store.ProjectModel) *ListAction {\n\treturn &ListAction{\n\t\tmodel: model,\n\t}\n}", "func NewController(bucket WalletBucket) BaseController {\n\tValidateWalletBucket(bucket)\n\treturn BaseController{bucket: bucket}\n}", "func (c WafAction) ToPtr() *WafAction {\n\treturn &c\n}", "func (t tApp) New(w http.ResponseWriter, r *http.Request, ctr, act string) *contr.App {\n\tc := &contr.App{}\n\tc.Controllers = Controllers.New(w, r, ctr, act)\n\treturn c\n}", "func NewActionAgent(\n\ttabletAlias topo.TabletAlias,\n\tdbcfgs *dbconfigs.DBConfigs,\n\tmycnf *mysqlctl.Mycnf,\n\tport, securePort int,\n\toverridesFile string,\n) (agent *ActionAgent, err error) {\n\tschemaOverrides := loadSchemaOverrides(overridesFile)\n\n\ttopoServer := topo.GetServer()\n\tmysqld := mysqlctl.NewMysqld(\"Dba\", mycnf, &dbcfgs.Dba, &dbcfgs.Repl)\n\n\tagent = &ActionAgent{\n\t\tTopoServer: topoServer,\n\t\tTabletAlias: tabletAlias,\n\t\tMysqld: mysqld,\n\t\tDBConfigs: dbcfgs,\n\t\tSchemaOverrides: schemaOverrides,\n\t\tdone: make(chan struct{}),\n\t\tHistory: history.New(historyLength),\n\t\tchangeItems: make(chan tabletChangeItem, 100),\n\t}\n\n\t// Start the binlog player services, not playing at start.\n\tagent.BinlogPlayerMap = NewBinlogPlayerMap(topoServer, &dbcfgs.App.ConnectionParams, mysqld)\n\tRegisterBinlogPlayerMap(agent.BinlogPlayerMap)\n\n\t// try to figure out the mysql port\n\tmysqlPort := mycnf.MysqlPort\n\tif mysqlPort == 0 {\n\t\t// we don't know the port, try to get it from mysqld\n\t\tvar err error\n\t\tmysqlPort, err = mysqld.GetMysqlPort()\n\t\tif err != nil {\n\t\t\tlog.Warningf(\"Cannot get current mysql port, will use 0 for now: %v\", err)\n\t\t}\n\t}\n\n\tif err := agent.Start(mysqlPort, port, securePort); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// register the RPC services from the agent\n\tagent.registerQueryService()\n\n\t// start health check if needed\n\tagent.initHeathCheck()\n\n\treturn agent, nil\n}", "func NewCookie(subCommands []*cobra.Command) *cobra.Command {\n\tvar cmd = cobra.Command{\n\t\tUse: \"cookie <command>\",\n\t\tShort: \"Cookie command group\",\n\t\tSilenceUsage: true,\n\t\tSilenceErrors: true,\n\t}\n\n\tcmd.AddCommand(subCommands...)\n\n\treturn &cmd\n}", "func CreateAction(req *http.Request) (interface{}, error) {\n\tparam, err := newCreateParam4Create(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn createActionProcess(req, param)\n}", "func NewFileAction(action string, path string) (*FileAction, error) {\n\tfa := new(FileAction)\n\tif err := fa.SetAction(action); err != nil {\n\t\treturn nil, err\n\t}\n\tfa.Path = path\n\treturn fa, nil\n}", "func NewCAPI(quit qu.C, timeout ...time.Duration) (c *CAPI) {\n\tc = &CAPI{quit: quit}\n\tif len(timeout)>0 {\n\t\tc.Timeout = timeout[0]\n\t} else {\n\t\tc.Timeout = time.Second * 5\n\t}\n\treturn \n}", "func newXactLLC(t cluster.Target, uuid string, bck cmn.Bck) *xactLLC {\n\treturn &xactLLC{xactBckBase: *newXactBckBase(uuid, cmn.ActLoadLomCache, bck, &mpather.JoggerGroupOpts{\n\t\tT: t,\n\t\tBck: bck,\n\t\tCTs: []string{fs.ObjectType},\n\t\tVisitObj: func(_ *cluster.LOM, _ []byte) error { return nil },\n\t\tDoLoad: mpather.Load,\n\t})}\n}", "func NewCreateGoalController(cgtRepos *persistence.Services, logger *log.Logger, authorizationService authorization.JwtService) Controller {\n\tcreateGoalUsecase := usecase.NewCreateGoalUsecase(&cgtRepos.Achiever, &cgtRepos.Goal, authorizationService)\n\n\tctrl := &createGoalController{\n\t\tUsecase: createGoalUsecase,\n\t\tLogger: logger,\n\t\tAuthorization: authorizationService,\n\t}\n\treturn ctrl\n}", "func NewCtrlJob(perfJob *perfv1alpha1.PerfJob, action string) *batchv1.Job {\n\tpodTemplate := makePodTemplate(perfJob.Spec.ControlImage, perfJob.Spec.Target, corev1.EnvVar{\n\t\tName: \"ACTION\",\n\t\tValue: action,\n\t})\n\treturn &batchv1.Job{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tGenerateName: \"ct-\" + perfJob.Name + \"-\",\n\t\t\tNamespace: perfJob.Namespace,\n\t\t\tLabels: JobLabels(perfJob.Name, action),\n\t\t\tOwnerReferences: []metav1.OwnerReference{\n\t\t\t\t*metav1.NewControllerRef(perfJob, perfv1alpha1.SchemeGroupVersion.WithKind(\"PerfJob\")),\n\t\t\t},\n\t\t},\n\t\tSpec: batchv1.JobSpec{\n\t\t\tTemplate: *podTemplate,\n\t\t},\n\t}\n}", "func (policy *ticketPolicy) OnCreateNewAccount(acc *types.Account) {\n}", "func (c *Clair) NewClairV3Layer(ctx context.Context, r *registry.Registry, image string, fsLayer distribution.Descriptor) (*clairpb.PostAncestryRequest_PostLayer, error) {\n\t// Form the path.\n\tp := strings.Join([]string{r.URL, \"v2\", image, \"blobs\", fsLayer.Digest.String()}, \"/\")\n\n\t// Get the headers.\n\th, err := r.Headers(ctx, p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &clairpb.PostAncestryRequest_PostLayer{\n\t\tHash: fsLayer.Digest.String(),\n\t\tPath: p,\n\t\tHeaders: h,\n\t}, nil\n}", "func NewWebhook(client kubernetes.Interface, resources *WebhookResources, controllerNamespace string, noInitContainer bool) (*Webhook, error) {\n\tvar (\n\t\tscheme = runtime.NewScheme()\n\t\tcodecs = serializer.NewCodecFactory(scheme)\n\t)\n\n\treturn &Webhook{\n\t\tdeserializer: codecs.UniversalDeserializer(),\n\t\tcontrollerNamespace: controllerNamespace,\n\t\tresources: resources,\n\t\tnoInitContainer: noInitContainer,\n\t}, nil\n}", "func CreateClanHandler(app *App) func(c echo.Context) error {\n\treturn func(c echo.Context) error {\n\t\tc.Set(\"route\", \"CreateClan\")\n\t\tstart := time.Now()\n\t\tgameID := c.Param(\"gameID\")\n\n\t\tlogger := app.Logger.With(\n\t\t\tzap.String(\"source\", \"clanHandler\"),\n\t\t\tzap.String(\"operation\", \"createClan\"),\n\t\t\tzap.String(\"gameID\", gameID),\n\t\t)\n\n\t\tvar payload CreateClanPayload\n\t\tif err := LoadJSONPayload(&payload, c, logger); err != nil {\n\t\t\tlog.E(logger, \"Failed to parse json payload.\", func(cm log.CM) {\n\t\t\t\tcm.Write(zap.Error(err))\n\t\t\t})\n\t\t\treturn FailWith(400, err.Error(), c)\n\t\t}\n\n\t\tgame, err := app.GetGame(c.StdContext(), gameID)\n\t\tif err != nil {\n\t\t\tlog.W(logger, \"Could not find game.\", func(cm log.CM) {\n\t\t\t\tcm.Write(zap.Error(err))\n\t\t\t})\n\t\t\treturn FailWith(404, err.Error(), c)\n\t\t}\n\n\t\tvar clan *models.Clan\n\t\tvar tx interfaces.Transaction\n\n\t\trollback := func(err error) error {\n\t\t\ttxErr := app.Rollback(tx, \"Creating clan failed\", c, logger, err)\n\t\t\tif txErr != nil {\n\t\t\t\treturn txErr\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}\n\n\t\ttx, err = app.BeginTrans(c.StdContext(), logger)\n\t\tif err != nil {\n\t\t\treturn FailWithError(err, c)\n\t\t}\n\n\t\tlog.D(logger, \"DB Tx begun successful.\")\n\n\t\tlog.D(logger, \"Creating clan...\")\n\t\tclan, err = models.CreateClan(\n\t\t\ttx,\n\t\t\tapp.EncryptionKey,\n\t\t\tgameID,\n\t\t\tpayload.PublicID,\n\t\t\tpayload.Name,\n\t\t\tpayload.OwnerPublicID,\n\t\t\tpayload.Metadata,\n\t\t\tpayload.AllowApplication,\n\t\t\tpayload.AutoJoin,\n\t\t\tgame.MaxClansPerPlayer,\n\t\t)\n\n\t\tif err != nil {\n\t\t\ttxErr := rollback(err)\n\t\t\tif txErr == nil {\n\t\t\t\tlog.E(logger, \"Create clan failed.\", func(cm log.CM) {\n\t\t\t\t\tcm.Write(zap.Error(err))\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn FailWithError(err, c)\n\t\t}\n\n\t\tclanJSON := map[string]interface{}{\n\t\t\t\"publicID\": clan.PublicID,\n\t\t\t\"name\": clan.Name,\n\t\t\t\"membershipCount\": clan.MembershipCount,\n\t\t\t\"ownerPublicID\": payload.OwnerPublicID,\n\t\t\t\"metadata\": clan.Metadata,\n\t\t\t\"allowApplication\": clan.AllowApplication,\n\t\t\t\"autoJoin\": clan.AutoJoin,\n\t\t}\n\n\t\tresult := map[string]interface{}{\n\t\t\t\"gameID\": gameID,\n\t\t\t\"clan\": clanJSON,\n\t\t}\n\n\t\tlog.D(logger, \"Dispatching hooks\")\n\t\terr = app.DispatchHooks(gameID, models.ClanCreatedHook, result)\n\t\tif err != nil {\n\t\t\ttxErr := rollback(err)\n\t\t\tif txErr == nil {\n\t\t\t\tlog.E(logger, \"Clan created hook dispatch failed.\", func(cm log.CM) {\n\t\t\t\t\tcm.Write(zap.Error(err))\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn FailWith(500, err.Error(), c)\n\t\t}\n\t\tlog.D(logger, \"Hook dispatched successfully.\")\n\n\t\terr = app.Commit(tx, \"Clan created\", c, logger)\n\t\tif err != nil {\n\t\t\treturn FailWith(500, err.Error(), c)\n\t\t}\n\n\t\tlog.D(logger, \"Clan created successfully.\", func(cm log.CM) {\n\t\t\tcm.Write(\n\t\t\t\tzap.String(\"clanPublicID\", clan.PublicID),\n\t\t\t\tzap.Duration(\"duration\", time.Now().Sub(start)),\n\t\t\t)\n\t\t})\n\n\t\treturn SucceedWith(map[string]interface{}{\n\t\t\t\"publicID\": clan.PublicID,\n\t\t}, c)\n\t}\n}", "func (c *Controller) AfterAction(action string) {\n}", "func (c *Controller) AfterAction(action string) {\n}", "func (o JobTemplateAbortCriteriaOutput) Action() JobTemplateActionOutput {\n\treturn o.ApplyT(func(v JobTemplateAbortCriteria) JobTemplateAction { return v.Action }).(JobTemplateActionOutput)\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 NewCampaignType(campaignTypeName, args string, cf *httpcli.Factory) (CampaignType, error) {\n\tcampaignTypeName = strings.ToLower(campaignTypeName)\n\n\tif cf == nil {\n\t\tcf = httpcli.NewFactory(\n\t\t\thttpcli.NewMiddleware(httpcli.ContextErrorMiddleware),\n\t\t\thttpcli.TracedTransportOpt,\n\t\t\thttpcli.NewCachedTransportOpt(httputil.Cache, true),\n\t\t)\n\t}\n\n\tcli, err := cf.Doer()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnormalizedArgs, err := validateArgs(campaignTypeName, args)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar ct CampaignType\n\n\tswitch campaignTypeName {\n\tcase \"comby\":\n\t\tc := &comby{\n\t\t\treplacerURL: graphqlbackend.ReplacerURL,\n\t\t\thttpClient: cli,\n\t\t\tfetchTimeout: defaultFetchTimeout,\n\t\t}\n\n\t\tif err := json.Unmarshal(normalizedArgs, &c.args); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tct = c\n\n\tcase \"credentials\":\n\t\tc := &credentials{newSearch: graphqlbackend.NewSearchImplementer}\n\n\t\tif err := json.Unmarshal(normalizedArgs, &c.args); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tct = c\n\n\tcase patchCampaignType:\n\t\t// Prefer the more specific createCampaignPlanFromPatches GraphQL API for creating campaigns\n\t\t// from patches computed by the caller, to avoid having multiple ways to do the same thing.\n\t\treturn nil, errors.New(\"use createCampaignPlanFromPatches for patch campaign types\")\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown campaign type: %s\", campaignTypeName)\n\t}\n\n\treturn ct, nil\n}", "func NewShowAction() *ShowAction {\n\treturn &ShowAction{}\n}", "func newWoc() *wfOperationCtx {\n\twf := &wfv1.Workflow{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"test-wf\",\n\t\t\tNamespace: \"default\",\n\t\t},\n\t}\n\twoc := wfOperationCtx{\n\t\twf: wf,\n\t\torig: wf.DeepCopyObject().(*wfv1.Workflow),\n\t\tupdated: false,\n\t\tlog: log.WithFields(log.Fields{\n\t\t\t\"workflow\": wf.ObjectMeta.Name,\n\t\t\t\"namespace\": wf.ObjectMeta.Namespace,\n\t\t}),\n\t\tcontroller: &WorkflowController{\n\t\t\tConfig: WorkflowControllerConfig{\n\t\t\t\tExecutorImage: \"executor:latest\",\n\t\t\t},\n\t\t\tclientset: fake.NewSimpleClientset(),\n\t\t},\n\t\tcompletedPods: make(map[string]bool),\n\t}\n\treturn &woc\n}", "func newBkCli() (*bkCli, error) {\n\tconfig := config.CurrentConfig()\n\n\tclient, err := newClient(config)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &bkCli{config, client}, nil\n}", "func (a *Agent) startNewAction() {\n\tactionTypes := a.mind.actionTypes()\n\n\thighestValue := 0.0\n\tvar bestActionTypes []actionType\n\tfor _, t := range actionTypes {\n\t\tisActive := false\n\t\t// if we currently have an active action, we do not want to start a new action\n\t\tfor _, ac := range a.activity.activeActions {\n\t\t\tif ac.getState() == actionStateActive {\n\t\t\t\tisActive = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif isActive {\n\t\t\treturn\n\t\t}\n\n\t\t// TODO what if an action cannot be started\n\t\t// highest value is to eat an apple, but there is no apple, we should somehow start thinking\n\t\t// about how to obtain an apple\n\n\t\tv := actionTypeValue(t)\n\t\tif v >= highestValue {\n\t\t\tcanStart := true\n\t\t\tfor startCond := range t.getConditions()[actionConditionTypeStart] {\n\t\t\t\tif !startCond.isSatisfied(a) {\n\t\t\t\t\tcanStart = false\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif canStart {\n\t\t\t\tif v > highestValue {\n\t\t\t\t\thighestValue = v\n\t\t\t\t\tbestActionTypes = []actionType{}\n\t\t\t\t}\n\t\t\t\tbestActionTypes = append(bestActionTypes, t)\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(bestActionTypes) == 0 {\n\t\treturn\n\t}\n\n\tbestActionType := bestActionTypes[rand.Intn(len(bestActionTypes))]\n\tfor startCondition := range bestActionType.getConditions()[actionConditionTypeStart] {\n\t\tif !startCondition.isSatisfied(a) {\n\t\t\treturn\n\t\t}\n\t}\n\n\tnewAction := bestActionType.instantiate().(action)\n\ta.activity.activeActions = append(a.activity.activeActions, newAction)\n\ta.mind.addItem(bestActionType, 1.0)\n\n\t// add pre-action conditions for hypothesis training\n\tfor cond := range a.getConditions() {\n\t\tpreActionConditions := newAction.getType().getConditions()[actionConditionTypeObservedAtStart]\n\t\tpreActionConditions[cond] = true\n\t\tnewAction.getPreConditions()[cond] = true\n\t}\n}", "func createPayback(args []string) {\n\n\tpaybackRepo := payback.NewRepository(persistence.GetGormClient())\n\ttxnRepo := transaction.NewRepository(persistence.GetGormClient())\n\tpaybackSVC := payback.NewPaybackService(paybackRepo, txnRepo)\n\terr := paybackSVC.CreatePayback(context.Background(), args)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\treturn\n\t}\n\tfmt.Println(\"Successfully added payback\")\n}", "func newChallengeValidationController(client *http.Client, webhooks []*Webhook) *challengeValidationController {\n\tscepHooks := []*Webhook{}\n\tfor _, wh := range webhooks {\n\t\tif wh.Kind != linkedca.Webhook_SCEPCHALLENGE.String() {\n\t\t\tcontinue\n\t\t}\n\t\tif !isCertTypeOK(wh) {\n\t\t\tcontinue\n\t\t}\n\t\tscepHooks = append(scepHooks, wh)\n\t}\n\treturn &challengeValidationController{\n\t\tclient: client,\n\t\twebhooks: scepHooks,\n\t}\n}", "func (l *ActionListener) Spawn(shutdown <-chan interface{}, actionID string) {\n\tdefer func() {\n\t\tglog.V(2).Infof(\"Action %s complete: \", actionID)\n\t\tif err := l.conn.Delete(l.GetPath(actionID)); err != nil {\n\t\t\tglog.Errorf(\"Could not delete %s: %s\", l.GetPath(actionID), err)\n\t\t}\n\t}()\n\n\tvar action Action\n\tif err := l.conn.Get(l.GetPath(actionID), &action); err != nil {\n\t\tglog.V(1).Infof(\"Could not get action %s: %s\", l.GetPath(actionID), err)\n\t\treturn\n\t}\n\n\tresult, err := l.handler.AttachAndRun(action.DockerID, action.Command)\n\tif result != nil && len(result) > 0 {\n\t\tglog.Info(string(result))\n\t}\n\tif err != nil {\n\t\tglog.Warningf(\"Error running command `%s` on container %s: %s\", action.Command, action.DockerID, err)\n\t} else {\n\t\tglog.V(1).Infof(\"Successfully ran command `%s` on container %s\", action.Command, action.DockerID)\n\t}\n}", "func generateAction(c *cli.Context) error {\n\tif c.NArg() != 1 {\n\t\treturn cli.NewExitError(fmt.Sprintf(\"%v %v requires exactly 1 argument\", c.App.Name, c.Command.Name), 1)\n\t}\n\n\tfilename, err := builder.CreateSkeletonFile(c.Args().First())\n\tif err != nil {\n\t\treturn cli.NewExitError(err, 1)\n\t}\n\n\tfmt.Printf(\"successfully created template file %v\\n\", filename)\n\n\treturn 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 NewHelloWorldAction(a application.HelloWorldApp) HelloWorldAction {\n\treturn &helloWorldAction{a: a}\n}", "func NewCleanProposal(cleaner potato.AccountName, proposalName potato.Name, maxCount uint64) *potato.Action {\n\ta := &potato.Action{\n\t\tAccount: ForumAN,\n\t\tName: ActN(\"clnproposal\"),\n\t\tAuthorization: []potato.PermissionLevel{\n\t\t\t{Actor: cleaner, Permission: potato.PermissionName(\"active\")},\n\t\t},\n\t\tActionData: potato.NewActionData(CleanProposal{\n\t\t\tProposalName: proposalName,\n\t\t\tMaxCount: maxCount,\n\t\t}),\n\t}\n\treturn a\n}", "func NewLogAction() Action {\n\treturn &logAction{}\n}" ]
[ "0.734408", "0.724161", "0.60927427", "0.5704581", "0.54267293", "0.5386312", "0.51870364", "0.5036263", "0.50139284", "0.49548915", "0.4951062", "0.49484608", "0.4876492", "0.48602346", "0.4833887", "0.48318735", "0.48297027", "0.47833982", "0.4767467", "0.47623938", "0.4719289", "0.4719289", "0.4697493", "0.46889588", "0.46835467", "0.4650522", "0.46418753", "0.4610552", "0.45990443", "0.4586414", "0.45854706", "0.45840746", "0.4554537", "0.45249128", "0.45164615", "0.44934005", "0.44514048", "0.44480854", "0.44468114", "0.44123504", "0.44041947", "0.43918198", "0.43844375", "0.43844274", "0.43667564", "0.43622604", "0.43574134", "0.4345762", "0.4343362", "0.43261817", "0.43113953", "0.430129", "0.42819157", "0.42723078", "0.4269948", "0.42578772", "0.42309302", "0.4218569", "0.4213352", "0.41987923", "0.41984352", "0.41715", "0.41679296", "0.4166326", "0.41608194", "0.41608194", "0.415489", "0.41412455", "0.4133739", "0.41255498", "0.4124562", "0.4113519", "0.4101679", "0.4100867", "0.4098282", "0.40980357", "0.40954185", "0.40933782", "0.40907773", "0.40756607", "0.40686998", "0.40665975", "0.4052688", "0.40465444", "0.40465444", "0.40409407", "0.403487", "0.40228257", "0.4017329", "0.40139058", "0.40070403", "0.40066713", "0.4003158", "0.39966774", "0.399393", "0.39925623", "0.39839995", "0.39767155", "0.39744112", "0.39734283" ]
0.8150347
0
TakeFromAccount implements the exported.ClawbackAction interface. It returns an error if the account is not at ClawbackVestingAccount or if the funder does not match.
TakeFromAccount реализует интерфейс exported.ClawbackAction. Он возвращает ошибку, если аккаунт не является ClawbackVestingAccount или если фундер не совпадает.
func (ca clawbackAction) TakeFromAccount(ctx sdk.Context, rawAccount exported.VestingAccount) error { cva, ok := rawAccount.(*ClawbackVestingAccount) if !ok { return sdkerrors.Wrapf(sdkerrors.ErrNotSupported, "clawback expects *ClawbackVestingAccount, got %T", rawAccount) } if ca.requestor.String() != cva.FunderAddress { return sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, "clawback can only be requested by original funder %s", cva.FunderAddress) } return cva.clawback(ctx, ca.dest, ca.ak, ca.bk, ca.sk) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (va *ClawbackVestingAccount) clawback(ctx sdk.Context, dest sdk.AccAddress, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) error {\n\t// Compute the clawback based on the account state only, and update account\n\ttoClawBack := va.computeClawback(ctx.BlockTime().Unix())\n\tif toClawBack.IsZero() {\n\t\treturn nil\n\t}\n\taddr := va.GetAddress()\n\tbondDenom := sk.BondDenom(ctx)\n\n\t// Compute the clawback based on bank balance and delegation, and update account\n\tencumbered := va.GetVestingCoins(ctx.BlockTime())\n\tbondedAmt := sk.GetDelegatorBonded(ctx, addr)\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, addr)\n\tbonded := sdk.NewCoins(sdk.NewCoin(bondDenom, bondedAmt))\n\tunbonding := sdk.NewCoins(sdk.NewCoin(bondDenom, unbondingAmt))\n\tunbonded := bk.GetAllBalances(ctx, addr)\n\ttoClawBack = va.updateDelegation(encumbered, toClawBack, bonded, unbonding, unbonded)\n\n\t// Write now now so that the bank module sees unvested tokens are unlocked.\n\t// Note that all store writes are aborted if there is a panic, so there is\n\t// no danger in writing incomplete results.\n\tak.SetAccount(ctx, va)\n\n\t// Now that future vesting events (and associated lockup) are removed,\n\t// the balance of the account is unlocked and can be freely transferred.\n\tspendable := bk.SpendableCoins(ctx, addr)\n\ttoXfer := coinsMin(toClawBack, spendable)\n\terr := bk.SendCoins(ctx, addr, dest, toXfer)\n\tif err != nil {\n\t\treturn err // shouldn't happen, given spendable check\n\t}\n\ttoClawBack = toClawBack.Sub(toXfer)\n\n\t// We need to traverse the staking data structures to update the\n\t// vesting account bookkeeping, and to recover more funds if necessary.\n\t// Staking is the only way unvested tokens should be missing from the bank balance.\n\n\t// If we need more, transfer UnbondingDelegations.\n\twant := toClawBack.AmountOf(bondDenom)\n\tunbondings := sk.GetUnbondingDelegations(ctx, addr, math.MaxUint16)\n\tfor _, unbonding := range unbondings {\n\t\tvalAddr, err := sdk.ValAddressFromBech32(unbonding.ValidatorAddress)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\ttransferred := sk.TransferUnbonding(ctx, addr, dest, valAddr, want)\n\t\twant = want.Sub(transferred)\n\t\tif !want.IsPositive() {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// If we need more, transfer Delegations.\n\tif want.IsPositive() {\n\t\tdelegations := sk.GetDelegatorDelegations(ctx, addr, math.MaxUint16)\n\t\tfor _, delegation := range delegations {\n\t\t\tvalidatorAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err) // shouldn't happen\n\t\t\t}\n\t\t\tvalidator, found := sk.GetValidator(ctx, validatorAddr)\n\t\t\tif !found {\n\t\t\t\t// validator has been removed\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\twantShares, err := validator.SharesFromTokensTruncated(want)\n\t\t\tif err != nil {\n\t\t\t\t// validator has no tokens\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttransferredShares := sk.TransferDelegation(ctx, addr, dest, delegation.GetValidatorAddr(), wantShares)\n\t\t\t// to be conservative in what we're clawing back, round transferred shares up\n\t\t\ttransferred := validator.TokensFromSharesRoundUp(transferredShares).RoundInt()\n\t\t\twant = want.Sub(transferred)\n\t\t\tif !want.IsPositive() {\n\t\t\t\t// Could be slightly negative, due to rounding?\n\t\t\t\t// Don't think so, due to the precautions above.\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// If we've transferred everything and still haven't transferred the desired clawback amount,\n\t// then the account must have most some unvested tokens from slashing.\n\treturn nil\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 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 (_Token *TokenTransactorSession) BurnFrom(account common.Address, amount *big.Int) (*types.Transaction, error) {\n\treturn _Token.Contract.BurnFrom(&_Token.TransactOpts, account, amount)\n}", "func (_Token *TokenTransactor) BurnFrom(opts *bind.TransactOpts, account common.Address, amount *big.Int) (*types.Transaction, error) {\n\treturn _Token.contract.Transact(opts, \"burnFrom\", account, amount)\n}", "func (sc Funcs) TransferAccountToChain(ctx wasmlib.ScFuncClientContext) *TransferAccountToChainCall {\n\tf := &TransferAccountToChainCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncTransferAccountToChain)}\n\tf.Params.Proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView)\n\treturn f\n}", "func (_ERC721Token *ERC721TokenTransactor) TakeOwnership(opts *bind.TransactOpts, _tokenId *big.Int) (*types.Transaction, error) {\n\treturn _ERC721Token.contract.Transact(opts, \"takeOwnership\", _tokenId)\n}", "func (_Token *TokenSession) BurnFrom(account common.Address, amount *big.Int) (*types.Transaction, error) {\n\treturn _Token.Contract.BurnFrom(&_Token.TransactOpts, account, amount)\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 (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 (s *Server) Transfer(ctx context.Context, req *pb.TransferRequest) (rep *pb.TransferReply, err error) {\n\trep = &pb.TransferReply{}\n\n\t// Get originator account and confirm it belongs to this RVASP\n\tvar account Account\n\tif err = LookupAccount(s.db, req.Account).First(&account).Error; err != nil {\n\t\tif errors.Is(err, gorm.ErrRecordNotFound) {\n\t\t\tlog.Info().Str(\"account\", req.Account).Msg(\"not found\")\n\t\t\treturn nil, status.Error(codes.NotFound, \"account not found\")\n\t\t}\n\t\tlog.Error().Err(err).Msg(\"could not lookup account\")\n\t\treturn nil, status.Errorf(codes.FailedPrecondition, \"could not lookup account: %s\", err)\n\t}\n\n\t// Identify the beneficiary either using the demo database or the directory service\n\tvar beneficiary Wallet\n\tif req.ExternalDemo {\n\t\tif req.BeneficiaryVasp == \"\" {\n\t\t\treturn nil, status.Error(codes.InvalidArgument, \"if external demo is true, must specify beneficiary vasp\")\n\t\t}\n\n\t\tbeneficiary = Wallet{\n\t\t\tProvider: VASP{\n\t\t\t\tName: req.BeneficiaryVasp,\n\t\t\t},\n\t\t}\n\t} else {\n\t\t// Lookup beneficiary wallet and confirm it belongs to a remote RVASP\n\t\tif err = LookupBeneficiary(s.db, req.Beneficiary).First(&beneficiary).Error; err != nil {\n\t\t\tif errors.Is(err, gorm.ErrRecordNotFound) {\n\t\t\t\tlog.Info().Str(\"beneficiary\", req.Beneficiary).Msg(\"not found\")\n\t\t\t\treturn nil, status.Error(codes.NotFound, \"beneficiary not found (use external_demo?)\")\n\t\t\t}\n\t\t\tlog.Error().Err(err).Msg(\"could not lookup beneficiary\")\n\t\t\treturn nil, status.Errorf(codes.FailedPrecondition, \"could not lookup beneficiary: %s\", err)\n\t\t}\n\n\t\tif req.CheckBeneficiary {\n\t\t\tif req.BeneficiaryVasp != beneficiary.Provider.Name {\n\t\t\t\tlog.Warn().\n\t\t\t\t\tStr(\"expected\", req.BeneficiaryVasp).\n\t\t\t\t\tStr(\"actual\", beneficiary.Provider.Name).\n\t\t\t\t\tMsg(\"check beneficiary failed\")\n\t\t\t\treturn nil, status.Error(codes.InvalidArgument, \"beneficiary wallet does not match beneficiary VASP\")\n\t\t\t}\n\n\t\t}\n\t}\n\n\t// Conduct a TRISADS lookup if necessary to get the endpoint\n\tvar peer *peers.Peer\n\tif peer, err = s.peers.Search(beneficiary.Provider.Name); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not search peer from directory service\")\n\t\treturn nil, status.Errorf(codes.Internal, \"could not search peer from directory service: %s\", err)\n\t}\n\n\t// Ensure that the local RVASP has signing keys for the remote, otherwise perform key exchange\n\tvar signKey *rsa.PublicKey\n\tif signKey, err = peer.ExchangeKeys(true); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not exchange keys with remote peer\")\n\t\treturn nil, status.Errorf(codes.FailedPrecondition, \"could not exchange keys with remote peer: %s\", err)\n\t}\n\n\t// Save the pending transaction and increment the accounts pending field\n\txfer := Transaction{\n\t\tEnvelope: uuid.New().String(),\n\t\tAccount: account,\n\t\tAmount: decimal.NewFromFloat32(req.Amount),\n\t\tDebit: true,\n\t\tCompleted: false,\n\t}\n\n\tif err = s.db.Save(&xfer).Error; err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not save transaction\")\n\t\treturn nil, status.Errorf(codes.FailedPrecondition, \"could not save transaction: %s\", err)\n\t}\n\n\t// Save the pending transaction on the account\n\t// TODO: remove pending transactions\n\taccount.Pending++\n\tif err = s.db.Save(&account).Error; err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not save originator account\")\n\t\treturn nil, status.Errorf(codes.FailedPrecondition, \"could not save originator account: %s\", err)\n\t}\n\n\t// Create an identity and transaction payload for TRISA exchange\n\ttransaction := &generic.Transaction{\n\t\tTxid: fmt.Sprintf(\"%d\", xfer.ID),\n\t\tOriginator: account.WalletAddress,\n\t\tBeneficiary: beneficiary.Address,\n\t\tAmount: float64(req.Amount),\n\t\tNetwork: \"TestNet\",\n\t\tTimestamp: xfer.Timestamp.Format(time.RFC3339),\n\t}\n\tidentity := &ivms101.IdentityPayload{\n\t\tOriginator: &ivms101.Originator{},\n\t\tOriginatingVasp: &ivms101.OriginatingVasp{},\n\t}\n\tif identity.OriginatingVasp.OriginatingVasp, err = s.vasp.LoadIdentity(); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not load originator vasp\")\n\t\treturn nil, status.Errorf(codes.Internal, \"could not load originator vasp: %s\", err)\n\t}\n\n\tidentity.Originator = &ivms101.Originator{\n\t\tOriginatorPersons: make([]*ivms101.Person, 0, 1),\n\t\tAccountNumbers: []string{account.WalletAddress},\n\t}\n\tvar originator *ivms101.Person\n\tif originator, err = account.LoadIdentity(); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not load originator identity\")\n\t\treturn nil, status.Errorf(codes.Internal, \"could not load originator identity: %s\", err)\n\t}\n\tidentity.Originator.OriginatorPersons = append(identity.Originator.OriginatorPersons, originator)\n\n\tpayload := &protocol.Payload{}\n\tif payload.Transaction, err = anypb.New(transaction); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not dump payload transaction\")\n\t\treturn nil, status.Errorf(codes.Internal, \"could not dump payload transaction: %s\", err)\n\t}\n\tif payload.Identity, err = anypb.New(identity); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not dump payload identity\")\n\t\treturn nil, status.Errorf(codes.Internal, \"could not dump payload identity: %s\", err)\n\t}\n\n\t// Secure the envelope with the remote beneficiary's signing keys\n\tvar envelope *protocol.SecureEnvelope\n\tif envelope, err = handler.New(xfer.Envelope, payload, nil).Seal(signKey); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not create or sign secure envelope\")\n\t\treturn nil, status.Errorf(codes.FailedPrecondition, \"could not create or sign secure envelope: %s\", err)\n\t}\n\n\t// Conduct the TRISA transaction, handle errors and send back to user\n\tif envelope, err = peer.Transfer(envelope); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not perform TRISA exchange\")\n\t\treturn nil, status.Errorf(codes.FailedPrecondition, \"could not perform TRISA exchange: %s\", err)\n\t}\n\n\t// Open the response envelope with local private keys\n\tvar opened *handler.Envelope\n\tif opened, err = handler.Open(envelope, s.trisa.sign); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not unseal TRISA response\")\n\t\treturn nil, status.Errorf(codes.FailedPrecondition, \"could not unseal TRISA response: %s\", err)\n\t}\n\n\t// Verify the contents of the response\n\tpayload = opened.Payload\n\tif payload.Identity == nil || payload.Transaction == nil {\n\t\tlog.Warn().Msg(\"did not receive identity or transaction\")\n\t\treturn nil, status.Error(codes.FailedPrecondition, \"no identity or transaction returned\")\n\t}\n\n\tif payload.Identity.TypeUrl != \"type.googleapis.com/ivms101.IdentityPayload\" {\n\t\tlog.Warn().Str(\"type\", payload.Identity.TypeUrl).Msg(\"unsupported identity type\")\n\t\treturn nil, status.Errorf(codes.FailedPrecondition, \"unsupported identity type for rVASP: %q\", payload.Identity.TypeUrl)\n\t}\n\n\tif payload.Transaction.TypeUrl != \"type.googleapis.com/trisa.data.generic.v1beta1.Transaction\" {\n\t\tlog.Warn().Str(\"type\", payload.Transaction.TypeUrl).Msg(\"unsupported transaction type\")\n\t\treturn nil, status.Errorf(codes.FailedPrecondition, \"unsupported identity type for rVASP: %q\", payload.Transaction.TypeUrl)\n\t}\n\n\tidentity = &ivms101.IdentityPayload{}\n\ttransaction = &generic.Transaction{}\n\tif err = payload.Identity.UnmarshalTo(identity); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not unmarshal identity\")\n\t\treturn nil, status.Errorf(codes.FailedPrecondition, \"could not unmarshal identity: %s\", err)\n\t}\n\tif err = payload.Transaction.UnmarshalTo(transaction); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not unmarshal transaction\")\n\t\treturn nil, status.Errorf(codes.FailedPrecondition, \"could not unmarshal transaction: %s\", err)\n\t}\n\n\t// Update the completed transaction and save to disk\n\txfer.Beneficiary = Identity{\n\t\tWalletAddress: transaction.Beneficiary,\n\t}\n\txfer.Completed = true\n\txfer.Timestamp, _ = time.Parse(time.RFC3339, transaction.Timestamp)\n\n\t// Serialize the identity information as JSON data\n\tvar data []byte\n\tif data, err = json.Marshal(identity); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not marshal IVMS 101 identity\")\n\t\treturn nil, status.Errorf(codes.Internal, \"could not marshal IVMS 101 identity: %s\", err)\n\t}\n\txfer.Identity = string(data)\n\n\tif err = s.db.Save(&xfer).Error; err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not save transaction\")\n\t\treturn nil, status.Errorf(codes.Internal, \"could not save transaction: %s\", err)\n\t}\n\n\t// Save the pending transaction on the account\n\t// TODO: remove pending transactions\n\taccount.Pending--\n\taccount.Completed++\n\taccount.Balance.Sub(xfer.Amount)\n\tif err = s.db.Save(&account).Error; err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not save originator account\")\n\t\treturn nil, status.Errorf(codes.Internal, \"could not save originator account: %s\", err)\n\t}\n\n\t// Return the transfer response\n\trep.Transaction = xfer.Proto()\n\treturn rep, nil\n}", "func (va ClawbackVestingAccount) postReward(ctx sdk.Context, reward sdk.Coins, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) {\n\t// Find the scheduled amount of vested and unvested staking tokens\n\tbondDenom := sk.BondDenom(ctx)\n\tvested := ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, ctx.BlockTime().Unix()).AmountOf(bondDenom)\n\tunvested := va.OriginalVesting.AmountOf(bondDenom).Sub(vested)\n\n\tif unvested.IsZero() {\n\t\t// no need to adjust the vesting schedule\n\t\treturn\n\t}\n\n\tif vested.IsZero() {\n\t\t// all staked tokens must be unvested\n\t\tva.distributeReward(ctx, ak, bondDenom, reward)\n\t\treturn\n\t}\n\n\t// Find current split of account balance on staking axis\n\tbonded := sk.GetDelegatorBonded(ctx, va.GetAddress())\n\tunbonding := sk.GetDelegatorUnbonding(ctx, va.GetAddress())\n\tdelegated := bonded.Add(unbonding)\n\n\t// discover what has been slashed and remove from delegated amount\n\toldDelegated := va.DelegatedVesting.AmountOf(bondDenom).Add(va.DelegatedFree.AmountOf(bondDenom))\n\tslashed := oldDelegated.Sub(intMin(oldDelegated, delegated))\n\tdelegated = delegated.Sub(intMin(delegated, slashed))\n\n\t// Prefer delegated tokens to be unvested\n\tunvested = intMin(unvested, delegated)\n\tvested = delegated.Sub(unvested)\n\n\t// Compute the unvested amount of reward and add to vesting schedule\n\tif unvested.IsZero() {\n\t\treturn\n\t}\n\tif vested.IsZero() {\n\t\tva.distributeReward(ctx, ak, bondDenom, reward)\n\t\treturn\n\t}\n\tunvestedRatio := unvested.ToDec().QuoTruncate(bonded.ToDec()) // round down\n\tunvestedReward := scaleCoins(reward, unvestedRatio)\n\tva.distributeReward(ctx, ak, bondDenom, unvestedReward)\n}", "func (_Registry *RegistryTransactor) SafeTransferAndClaimFrom(opts *bind.TransactOpts, _from common.Address, _to common.Address, _id *big.Int, _value *big.Int, _data []byte, _claimData []byte) (*types.Transaction, error) {\n\treturn _Registry.contract.Transact(opts, \"safeTransferAndClaimFrom\", _from, _to, _id, _value, _data, _claimData)\n}", "func (_ZKOnacci *ZKOnacciTransactorSession) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _ZKOnacci.Contract.SafeTransferFrom(&_ZKOnacci.TransactOpts, from, to, tokenId)\n}", "func Transfertobankaccount(v float64) predicate.Bulk {\n\treturn predicate.Bulk(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldTransfertobankaccount), v))\n\t})\n}", "func (_CraftingI *CraftingITransactorSession) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _CraftingI.Contract.SafeTransferFrom(&_CraftingI.TransactOpts, from, to, tokenId)\n}", "func transfer_ (stub shim.ChaincodeStubInterface, from_account_name string, to_account_name string, amount int) error {\n if amount < 0 {\n return fmt.Errorf(\"Can't transfer a negative amount (%d)\", amount)\n }\n from_account,err := get_account_(stub, from_account_name)\n if err != nil {\n return fmt.Errorf(\"Error in retrieving \\\"from\\\" account \\\"%s\\\"; %v\", from_account_name, err.Error())\n }\n to_account,err := get_account_(stub, to_account_name)\n if err != nil {\n return fmt.Errorf(\"Error in retrieving \\\"to\\\" account \\\"%s\\\"; %v\", to_account_name, err.Error())\n }\n if from_account.Balance < amount {\n return fmt.Errorf(\"Can't transfer; \\\"from\\\" account balance (%d) is less than transfer amount (%d)\", from_account.Balance, amount)\n }\n\n from_account.Balance -= amount\n to_account.Balance += amount\n\n err = overwrite_account_(stub, from_account)\n if err != nil {\n return fmt.Errorf(\"Could not transfer from account %v; error was %v\", *from_account, err.Error())\n }\n\n err = overwrite_account_(stub, to_account)\n if err != nil {\n return fmt.Errorf(\"Could not transfer to account %v; error was %v\", *to_account, err.Error())\n }\n\n return nil\n}", "func (s *SmartContract) TransferFrom(ctx contractapi.TransactionContextInterface, from string, to string, value int) error {\n\n\t// Get ID of submitting client identity\n\tspender, err := ctx.GetClientIdentity().GetID()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get client id: %v\", err)\n\t}\n\n\t// Create allowanceKey\n\tallowanceKey, err := ctx.GetStub().CreateCompositeKey(allowancePrefix, []string{from, spender})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create the composite key for prefix %s: %v\", allowancePrefix, err)\n\t}\n\n\t// Retrieve the allowance of the spender\n\tcurrentAllowanceBytes, err := ctx.GetStub().GetState(allowanceKey)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to retrieve the allowance for %s from world state: %v\", allowanceKey, err)\n\t}\n\n\tvar currentAllowance int\n\tcurrentAllowance, _ = strconv.Atoi(string(currentAllowanceBytes)) // Error handling not needed since Itoa() was used when setting the totalSupply, guaranteeing it was an integer.\n\n\t// Check if transferred value is less than allowance\n\tif currentAllowance < value {\n\t\treturn fmt.Errorf(\"spender does not have enough allowance for transfer\")\n\t}\n\n\t// Initiate the transfer\n\terr = transferHelper(ctx, from, to, value)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to transfer: %v\", err)\n\t}\n\n\t// Decrease the allowance\n\tupdatedAllowance := currentAllowance - value\n\terr = ctx.GetStub().PutState(allowanceKey, []byte(strconv.Itoa(updatedAllowance)))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Emit the Transfer event\n\ttransferEvent := event{from, to, value}\n\ttransferEventJSON, err := json.Marshal(transferEvent)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to obtain JSON encoding: %v\", err)\n\t}\n\terr = ctx.GetStub().SetEvent(\"Transfer\", transferEventJSON)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to set event: %v\", err)\n\t}\n\n\tlog.Printf(\"spender %s allowance updated from %d to %d\", spender, currentAllowance, updatedAllowance)\n\n\treturn nil\n}", "func (_ZKOnacci *ZKOnacciTransactor) SafeTransferFrom(opts *bind.TransactOpts, from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _ZKOnacci.contract.Transact(opts, \"safeTransferFrom\", from, to, tokenId)\n}", "func (_CraftingI *CraftingISession) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _CraftingI.Contract.SafeTransferFrom(&_CraftingI.TransactOpts, from, to, tokenId)\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 (_ZKOnacci *ZKOnacciSession) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _ZKOnacci.Contract.SafeTransferFrom(&_ZKOnacci.TransactOpts, from, to, tokenId)\n}", "func (_SweetToken *SweetTokenTransactorSession) TransferFrom(src common.Address, dst common.Address, wad *big.Int) (*types.Transaction, error) {\n\treturn _SweetToken.Contract.TransferFrom(&_SweetToken.TransactOpts, src, dst, wad)\n}", "func (_Registry *RegistryTransactorSession) SafeTransferAndClaimFrom(_from common.Address, _to common.Address, _id *big.Int, _value *big.Int, _data []byte, _claimData []byte) (*types.Transaction, error) {\n\treturn _Registry.Contract.SafeTransferAndClaimFrom(&_Registry.TransactOpts, _from, _to, _id, _value, _data, _claimData)\n}", "func (_MainnetCryptoCardsContract *MainnetCryptoCardsContractTransactorSession) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int, _data []byte) (*types.Transaction, error) {\n\treturn _MainnetCryptoCardsContract.Contract.SafeTransferFrom(&_MainnetCryptoCardsContract.TransactOpts, from, to, tokenId, _data)\n}", "func (_MainnetCryptoCardsContract *MainnetCryptoCardsContractTransactor) SafeTransferFrom(opts *bind.TransactOpts, from common.Address, to common.Address, tokenId *big.Int, _data []byte) (*types.Transaction, error) {\n\treturn _MainnetCryptoCardsContract.contract.Transact(opts, \"safeTransferFrom\", from, to, tokenId, _data)\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 (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 (controller *Auth) safeRedilectAccount(sendMe string) {\n\tvar safeAddress string\n\tsafeAddress = controller.getSafeURL(sendMe)\n\tcontroller.Redirect(safeAddress, 302)\n}", "func (oc *contractTransmitter) FromAccount() (ocrtypes.Account, error) {\n\treturn ocrtypes.Account(oc.transmitter.FromAddress().String()), nil\n}", "func (_CraftingI *CraftingITransactor) SafeTransferFrom(opts *bind.TransactOpts, from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _CraftingI.contract.Transact(opts, \"safeTransferFrom\", from, to, tokenId)\n}", "func (_Registry *RegistrySession) SafeTransferAndClaimFrom(_from common.Address, _to common.Address, _id *big.Int, _value *big.Int, _data []byte, _claimData []byte) (*types.Transaction, error) {\n\treturn _Registry.Contract.SafeTransferAndClaimFrom(&_Registry.TransactOpts, _from, _to, _id, _value, _data, _claimData)\n}", "func (_MainnetCryptoCardsContract *MainnetCryptoCardsContractSession) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int, _data []byte) (*types.Transaction, error) {\n\treturn _MainnetCryptoCardsContract.Contract.SafeTransferFrom(&_MainnetCryptoCardsContract.TransactOpts, from, to, tokenId, _data)\n}", "func (_SweetToken *SweetTokenSession) TransferFrom(src common.Address, dst common.Address, wad *big.Int) (*types.Transaction, error) {\n\treturn _SweetToken.Contract.TransferFrom(&_SweetToken.TransactOpts, src, dst, wad)\n}", "func (_SweetToken *SweetTokenTransactor) TransferFrom(opts *bind.TransactOpts, src common.Address, dst common.Address, wad *big.Int) (*types.Transaction, error) {\n\treturn _SweetToken.contract.Transact(opts, \"transferFrom\", src, dst, wad)\n}", "func (sc Funcs) TransferAllowanceTo(ctx wasmlib.ScFuncClientContext) *TransferAllowanceToCall {\n\tf := &TransferAllowanceToCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncTransferAllowanceTo)}\n\tf.Params.Proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView)\n\treturn f\n}", "func (_DetailedTestToken *DetailedTestTokenTransactorSession) Burn(_from common.Address, _amount *big.Int) (*types.Transaction, error) {\n\treturn _DetailedTestToken.Contract.Burn(&_DetailedTestToken.TransactOpts, _from, _amount)\n}", "func (_DetailedTestToken *DetailedTestTokenTransactor) Burn(opts *bind.TransactOpts, _from common.Address, _amount *big.Int) (*types.Transaction, error) {\n\treturn _DetailedTestToken.contract.Transact(opts, \"burn\", _from, _amount)\n}", "func NewClawbackAction(requestor, dest sdk.AccAddress, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) exported.ClawbackAction {\n\treturn clawbackAction{\n\t\trequestor: requestor,\n\t\tdest: dest,\n\t\tak: ak,\n\t\tbk: bk,\n\t\tsk: sk,\n\t}\n}", "func (va ClawbackVestingAccount) GetFunder() sdk.AccAddress {\n\taddr, err := sdk.AccAddressFromBech32(va.FunderAddress)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn addr\n}", "func BankAccount(val string) Argument {\n\treturn func(request *requests.Request) error {\n\t\trequest.AddArgument(\"bank_account\", val)\n\t\treturn nil\n\t}\n}", "func (_DetailedTestToken *DetailedTestTokenSession) Burn(_from common.Address, _amount *big.Int) (*types.Transaction, error) {\n\treturn _DetailedTestToken.Contract.Burn(&_DetailedTestToken.TransactOpts, _from, _amount)\n}", "func (_ElvTradable *ElvTradableTransactor) SafeTransferFrom(opts *bind.TransactOpts, from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _ElvTradable.contract.Transact(opts, \"safeTransferFrom\", from, to, tokenId)\n}", "func (_Wmatic *WmaticTransactorSession) TransferFrom(src common.Address, dst common.Address, wad *big.Int) (*types.Transaction, error) {\n\treturn _Wmatic.Contract.TransferFrom(&_Wmatic.TransactOpts, src, dst, wad)\n}", "func (s *StorageInMemory) Transfer(accountFrom, accountTo storage.AccountID, amountToTransfer storage.AccountBalance) error {\n\tbalanceFrom, err := s.getBalance(accountFrom)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbalanceTo, err := s.getBalance(accountTo)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbalanceFrom.mu.Lock()\n\tbalanceTo.mu.Lock()\n\tdefer balanceFrom.mu.Unlock()\n\tdefer balanceTo.mu.Unlock()\n\n\tif balanceFrom.amount < amountToTransfer {\n\t\treturn ErrNotEnoughBalance\n\t}\n\t// todo del (для отладки)\n\t// fmt.Println(\"операция: \", balanceFrom.amount, balanceTo.amount, balanceFrom.amount+balanceTo.amount)\n\tbalanceFrom.amount -= amountToTransfer\n\tbalanceTo.amount += amountToTransfer\n\treturn nil\n}", "func Transfer(from, to string, amount int64) error {\n\tif amount <= 0 {\n\t\treturn fmt.Errorf(\"invalid amount; %d\", amount)\n\t}\n\n\tvar accs []*share.Account\n\terr := client.GetByNames(ctx, share.KindAccount, []string{from, to}, &accs)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"get accounts error; %v\", err)\n\t}\n\n\tif accs[0].Balance < amount {\n\t\treturn fmt.Errorf(\"balance of account %s is %d, not enough for withdraw %d\", from, accs[0].Balance, amount)\n\t}\n\n\taccs[0].Balance -= amount\n\taccs[1].Balance += amount\n\ttrans := []*share.Transaction{\n\t\t{Type: share.TransactionTypeWithdraw, AccountID: from, Amount: -amount},\n\t\t{Type: share.TransactionTypeDeposit, AccountID: to, Amount: amount},\n\t}\n\tfor _, tran := range trans {\n\t\ttran.NewKey(share.KindTransaction)\n\t}\n\terr = client.SaveModels(ctx, \"\", []interface{}{accs[0], accs[1], trans[0], trans[1]})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"save models error; %v\", err)\n\t}\n\treturn nil\n}", "func Burn(ctx contractapi.TransactionContextInterface, amount int) error {\n\n\t// Check minter authorization - this sample assumes Org1 is the central banker with privilege to burn new tokens\n\tclientMSPID, err := ctx.GetClientIdentity().GetMSPID()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get MSPID: %v\", err)\n\t}\n\tif clientMSPID != \"Org1MSP\" {\n\t\treturn fmt.Errorf(\"client is not authorized to mint new tokens\")\n\t}\n\n\t// Get ID of submitting client identity\n\tburner, err := ctx.GetClientIdentity().GetID()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get client id: %v\", err)\n\t}\n\n\tif amount <= 0 {\n\t\treturn errors.New(\"burn amount must be a positive integer\")\n\t}\n\n\tcurrentBalanceBytes, err := ctx.GetStub().GetState(burner)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to read burner account %s from world state: %v\", burner, err)\n\t}\n\n\tvar currentBalance int\n\n\t// Check if burner current balance exists\n\tif currentBalanceBytes == nil {\n\t\treturn errors.New(\"the balance does not exist\")\n\t}\n\n\tcurrentBalance, _ = strconv.Atoi(string(currentBalanceBytes)) // Error handling not needed since Itoa() was used when setting the account balance, guaranteeing it was an integer.\n\n\tupdatedBalance := currentBalance - amount\n\n\terr = ctx.GetStub().PutState(burner, []byte(strconv.Itoa(updatedBalance)))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Update the totalSupply\n\ttotalSupplyBytes, err := ctx.GetStub().GetState(totalSupplyKey)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to retrieve total token supply: %v\", err)\n\t}\n\n\t// If no tokens have been burned, throw error\n\tif totalSupplyBytes == nil {\n\t\treturn errors.New(\"totalSupply does not exist\")\n\t}\n\n\ttotalSupply, _ := strconv.Atoi(string(totalSupplyBytes)) // Error handling not needed since Itoa() was used when setting the totalSupply, guaranteeing it was an integer.\n\n\t// Subtract the burn amount to the total supply and update the state\n\ttotalSupply -= amount\n\terr = ctx.GetStub().PutState(totalSupplyKey, []byte(strconv.Itoa(totalSupply)))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Emit the Transfer event\n\ttransferEvent := event{burner, \"0x0\", amount}\n\ttransferEventJSON, err := json.Marshal(transferEvent)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to obtain JSON encoding: %v\", err)\n\t}\n\terr = ctx.GetStub().SetEvent(\"Transfer\", transferEventJSON)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to set event: %v\", err)\n\t}\n\n\tlog.Printf(\"burner account %s balance updated from %d to %d\", burner, currentBalance, updatedBalance)\n\n\treturn nil\n}", "func (_ERC721Token *ERC721TokenTransactorSession) TakeOwnership(_tokenId *big.Int) (*types.Transaction, error) {\n\treturn _ERC721Token.Contract.TakeOwnership(&_ERC721Token.TransactOpts, _tokenId)\n}", "func (_Cakevault *CakevaultSession) TransferOwnership(newOwner common.Address) (*types.Transaction, error) {\n\treturn _Cakevault.Contract.TransferOwnership(&_Cakevault.TransactOpts, newOwner)\n}", "func (_Harberger *HarbergerTransactor) TransferToVault(opts *bind.TransactOpts, _token common.Address) (*types.Transaction, error) {\n\treturn _Harberger.contract.Transact(opts, \"transferToVault\", _token)\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 (_IERC721 *IERC721TransactorSession) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _IERC721.Contract.SafeTransferFrom(&_IERC721.TransactOpts, from, to, tokenId)\n}", "func (_IERC721 *IERC721TransactorSession) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _IERC721.Contract.SafeTransferFrom(&_IERC721.TransactOpts, from, to, tokenId)\n}", "func (_StakingToken *StakingTokenTransactorSession) TransferFrom(sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) {\n\treturn _StakingToken.Contract.TransferFrom(&_StakingToken.TransactOpts, sender, recipient, amount)\n}", "func (_DetailedTestToken *DetailedTestTokenTransactorSession) TransferFrom(sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) {\n\treturn _DetailedTestToken.Contract.TransferFrom(&_DetailedTestToken.TransactOpts, sender, recipient, amount)\n}", "func (_ERC721Token *ERC721TokenSession) TakeOwnership(_tokenId *big.Int) (*types.Transaction, error) {\n\treturn _ERC721Token.Contract.TakeOwnership(&_ERC721Token.TransactOpts, _tokenId)\n}", "func (_Cakevault *CakevaultTransactorSession) TransferOwnership(newOwner common.Address) (*types.Transaction, error) {\n\treturn _Cakevault.Contract.TransferOwnership(&_Cakevault.TransactOpts, newOwner)\n}", "func (_CrToken *CrTokenTransactorSession) TransferFrom(src common.Address, dst common.Address, amount *big.Int) (*types.Transaction, error) {\n\treturn _CrToken.Contract.TransferFrom(&_CrToken.TransactOpts, src, dst, amount)\n}", "func (_ERC721 *ERC721TransactorSession) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _ERC721.Contract.SafeTransferFrom(&_ERC721.TransactOpts, from, to, tokenId)\n}", "func (_Harberger *HarbergerTransactorSession) TransferToVault(_token common.Address) (*types.Transaction, error) {\n\treturn _Harberger.Contract.TransferToVault(&_Harberger.TransactOpts, _token)\n}", "func (_Cakevault *CakevaultTransactor) TransferOwnership(opts *bind.TransactOpts, newOwner common.Address) (*types.Transaction, error) {\n\treturn _Cakevault.contract.Transact(opts, \"transferOwnership\", newOwner)\n}", "func (_Contract *ContractTransactorSession) SafeTransferFrom(_from common.Address, _to common.Address, _tokenId *big.Int, _data []byte) (*types.Transaction, error) {\n\treturn _Contract.Contract.SafeTransferFrom(&_Contract.TransactOpts, _from, _to, _tokenId, _data)\n}", "func (_ElvTradableLocal *ElvTradableLocalTransactor) SafeTransferFrom(opts *bind.TransactOpts, from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _ElvTradableLocal.contract.Transact(opts, \"safeTransferFrom\", from, to, tokenId)\n}", "func (_Wmatic *WmaticSession) TransferFrom(src common.Address, dst common.Address, wad *big.Int) (*types.Transaction, error) {\n\treturn _Wmatic.Contract.TransferFrom(&_Wmatic.TransactOpts, src, dst, wad)\n}", "func (_MainnetCryptoCardsContract *MainnetCryptoCardsContractTransactorSession) TransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _MainnetCryptoCardsContract.Contract.TransferFrom(&_MainnetCryptoCardsContract.TransactOpts, from, to, tokenId)\n}", "func (_ProjectWalletAuthoriser *ProjectWalletAuthoriserTransactor) TransferOwnership(opts *bind.TransactOpts, _newOwner common.Address) (*types.Transaction, error) {\n\treturn _ProjectWalletAuthoriser.contract.Transact(opts, \"transferOwnership\", _newOwner)\n}", "func (_FixedSupplyToken *FixedSupplyTokenTransactor) TransferOwnership(opts *bind.TransactOpts, _newOwner common.Address) (*types.Transaction, error) {\n\treturn _FixedSupplyToken.contract.Transact(opts, \"transferOwnership\", _newOwner)\n}", "func (_DetailedTestToken *DetailedTestTokenTransactor) TransferOwnership(opts *bind.TransactOpts, newOwner common.Address) (*types.Transaction, error) {\n\treturn _DetailedTestToken.contract.Transact(opts, \"transferOwnership\", newOwner)\n}", "func transfer(w http.ResponseWriter, r *http.Request) {\n\tpayload, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\twriteErrorResponse(w, http.StatusBadRequest, \"failed to read request body: %s\", err)\n\t\treturn\n\t}\n\n\tvar transfer api.Transfer\n\tif err := json.Unmarshal(payload, &transfer); err != nil {\n\t\twriteErrorResponse(w, http.StatusBadRequest, \"failed to parse payload json: %s\", err)\n\t\treturn\n\t}\n\n\targs := []string{\n\t\t\"set_owner\",\n\t\ttransfer.MarbleId,\n\t\ttransfer.ToOwnerId,\n\t}\n\n\tdata, err := fc.InvokeCC(ConsortiumChannelID, MarblesCC, args, nil)\n\tif err != nil {\n\t\twriteErrorResponse(w, http.StatusInternalServerError, \"cc invoke failed: %s: %v\", err, args)\n\t\treturn\n\t}\n\tresponse := api.Response{\n\t\tId: transfer.MarbleId,\n\t\tTxId: data.FabricTxnID,\n\t}\n\twriteJSONResponse(w, http.StatusOK, response)\n}", "func (_IERC721Metadata *IERC721MetadataTransactorSession) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _IERC721Metadata.Contract.SafeTransferFrom(&_IERC721Metadata.TransactOpts, from, to, tokenId)\n}", "func (_DetailedTestToken *DetailedTestTokenSession) TransferFrom(sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) {\n\treturn _DetailedTestToken.Contract.TransferFrom(&_DetailedTestToken.TransactOpts, sender, recipient, amount)\n}", "func (_CraftingI *CraftingITransactorSession) TransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _CraftingI.Contract.TransferFrom(&_CraftingI.TransactOpts, from, to, tokenId)\n}", "func (_Harberger *HarbergerSession) TransferToVault(_token common.Address) (*types.Transaction, error) {\n\treturn _Harberger.Contract.TransferToVault(&_Harberger.TransactOpts, _token)\n}", "func (_MainnetCryptoCardsContract *MainnetCryptoCardsContractTransactor) TransferFrom(opts *bind.TransactOpts, from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _MainnetCryptoCardsContract.contract.Transact(opts, \"transferFrom\", from, to, tokenId)\n}", "func (_FixedSupplyToken *FixedSupplyTokenTransactorSession) TransferFrom(from common.Address, to common.Address, tokens *big.Int) (*types.Transaction, error) {\n\treturn _FixedSupplyToken.Contract.TransferFrom(&_FixedSupplyToken.TransactOpts, from, to, tokens)\n}", "func (_ERC721Enumerable *ERC721EnumerableTransactor) SafeTransferFrom(opts *bind.TransactOpts, from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _ERC721Enumerable.contract.Transact(opts, \"safeTransferFrom\", from, to, tokenId)\n}", "func (_SimpleReadAccessController *SimpleReadAccessControllerTransactor) TransferOwnership(opts *bind.TransactOpts, _to common.Address) (*types.Transaction, error) {\n\treturn _SimpleReadAccessController.contract.Transact(opts, \"transferOwnership\", _to)\n}", "func (_WELV9 *WELV9Transactor) TransferFrom(opts *bind.TransactOpts, src common.Address, dst common.Address, wad *big.Int) (*types.Transaction, error) {\n\treturn _WELV9.contract.Transact(opts, \"transferFrom\", src, dst, wad)\n}", "func (_StakingToken *StakingTokenSession) TransferFrom(sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) {\n\treturn _StakingToken.Contract.TransferFrom(&_StakingToken.TransactOpts, sender, recipient, amount)\n}", "func (_ERC721 *ERC721TransactorSession) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int, _data []byte) (*types.Transaction, error) {\n\treturn _ERC721.Contract.SafeTransferFrom(&_ERC721.TransactOpts, from, to, tokenId, _data)\n}", "func (_BurnableToken *BurnableTokenTransactorSession) TransferFrom(_from common.Address, _to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BurnableToken.Contract.TransferFrom(&_BurnableToken.TransactOpts, _from, _to, _value)\n}", "func (_Contract *ContractSession) SafeTransferFrom(_from common.Address, _to common.Address, _tokenId *big.Int, _data []byte) (*types.Transaction, error) {\n\treturn _Contract.Contract.SafeTransferFrom(&_Contract.TransactOpts, _from, _to, _tokenId, _data)\n}", "func (_IERC721 *IERC721Session) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _IERC721.Contract.SafeTransferFrom(&_IERC721.TransactOpts, from, to, tokenId)\n}", "func (_IERC721 *IERC721Session) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _IERC721.Contract.SafeTransferFrom(&_IERC721.TransactOpts, from, to, tokenId)\n}", "func Withdraw(card types.Card, amount types.Money) types.Card {\n \n if (card.Active) && (card.Balance >= amount) && (amount > 0) && (amount <= 2_000_000) {\n\t\tcard.Balance = card.Balance - amount \n }\n\n return card\n}", "func FundAccount(address string) error {\n\tresp, err := http.Get(\"https://friendbot.zion.info/?addr=\" + address)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"requesting friendbot lumens\")\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"reading response from bad friendbot request %d\", resp.StatusCode)\n\t\t}\n\t\treturn fmt.Errorf(\"error funding address through friendbot. got bad status code %d, response %s\", resp.StatusCode, body)\n\t}\n\treturn nil\n}", "func (_BaseAccessWalletFactory *BaseAccessWalletFactoryTransactor) TransferOwnership(opts *bind.TransactOpts, newOwner common.Address) (*types.Transaction, error) {\n\treturn _BaseAccessWalletFactory.contract.Transact(opts, \"transferOwnership\", newOwner)\n}", "func (_IERC721Metadata *IERC721MetadataSession) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _IERC721Metadata.Contract.SafeTransferFrom(&_IERC721Metadata.TransactOpts, from, to, tokenId)\n}", "func (theAccount *Account) Withdraw(amount int) error {\n\tif theAccount.balance < amount {\n\t\treturn errNoMoney\n\t}\n\ttheAccount.balance -= amount\n\treturn nil\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 (_FeeCurrencyWhitelist *FeeCurrencyWhitelistTransactor) TransferOwnership(opts *bind.TransactOpts, newOwner common.Address) (*types.Transaction, error) {\n\treturn _FeeCurrencyWhitelist.contract.Transact(opts, \"transferOwnership\", newOwner)\n}", "func (_SimpleSavingsWallet *SimpleSavingsWalletTransactor) TransferOwnership(opts *bind.TransactOpts, newOwner common.Address) (*types.Transaction, error) {\n\treturn _SimpleSavingsWallet.contract.Transact(opts, \"transferOwnership\", newOwner)\n}", "func (o *Filesystem) TakeOwnership(ctx context.Context, options map[string]dbus.Variant) (err error) {\n\terr = o.object.CallWithContext(ctx, InterfaceFilesystem+\".TakeOwnership\", 0, options).Store()\n\treturn\n}", "func (_StaticCallProxy *StaticCallProxyCallerSession) TransferFrom(assetData []byte, from common.Address, to common.Address, amount *big.Int) error {\n\treturn _StaticCallProxy.Contract.TransferFrom(&_StaticCallProxy.CallOpts, assetData, from, to, amount)\n}", "func (_ERC721 *ERC721Transactor) SafeTransferFrom(opts *bind.TransactOpts, from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _ERC721.contract.Transact(opts, \"safeTransferFrom\", from, to, tokenId)\n}", "func (_ERC721 *ERC721Transactor) SafeTransferFrom(opts *bind.TransactOpts, from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _ERC721.contract.Transact(opts, \"safeTransferFrom\", from, to, tokenId)\n}", "func (_MainnetCryptoCardsContract *MainnetCryptoCardsContractSession) TransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _MainnetCryptoCardsContract.Contract.TransferFrom(&_MainnetCryptoCardsContract.TransactOpts, from, to, tokenId)\n}", "func (_BurnableToken *BurnableTokenTransactor) TransferOwnership(opts *bind.TransactOpts, newOwner common.Address) (*types.Transaction, error) {\n\treturn _BurnableToken.contract.Transact(opts, \"transferOwnership\", newOwner)\n}", "func (account *Account) Withdraw(amount int) error {\r\n\tif account.balance < amount {\r\n\t\t// return errors.New(\"Can't widthdraw amount is more than yout balance\")\r\n\t\treturn errNoMoney\r\n\t}\r\n\taccount.balance -= amount\r\n\treturn nil\r\n\t// nill is null or None\r\n\r\n}", "func (_IERC721Enumerable *IERC721EnumerableTransactor) SafeTransferFrom(opts *bind.TransactOpts, from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _IERC721Enumerable.contract.Transact(opts, \"safeTransferFrom\", from, to, tokenId)\n}" ]
[ "0.6373067", "0.61946815", "0.52225226", "0.5115219", "0.5063567", "0.50280553", "0.50247216", "0.5002626", "0.49813092", "0.49658814", "0.4900447", "0.48946452", "0.48875058", "0.48761022", "0.48605388", "0.48496777", "0.48311484", "0.48254326", "0.48169035", "0.48071176", "0.48055145", "0.47890434", "0.4785375", "0.4783107", "0.4761969", "0.47608122", "0.4742863", "0.47302884", "0.47296655", "0.4724775", "0.4707527", "0.47068688", "0.46969882", "0.46838152", "0.46719366", "0.4662192", "0.46529555", "0.4639384", "0.46223053", "0.4611176", "0.46052802", "0.45961925", "0.45717075", "0.45622805", "0.45550978", "0.4554389", "0.45536426", "0.4552938", "0.45240572", "0.45093474", "0.45085338", "0.4489931", "0.4489931", "0.4487042", "0.44748864", "0.44681934", "0.4463701", "0.44635332", "0.44627368", "0.44619653", "0.44586185", "0.4453211", "0.44306096", "0.4424686", "0.4418643", "0.44108614", "0.44090188", "0.44063455", "0.4405336", "0.44042626", "0.4403091", "0.44001493", "0.4399725", "0.4396146", "0.4393432", "0.4382249", "0.43819675", "0.43806216", "0.4373875", "0.4370931", "0.4370198", "0.43660256", "0.43658015", "0.43658015", "0.4357969", "0.43576732", "0.43557364", "0.43541232", "0.43538067", "0.43534416", "0.4353307", "0.4350261", "0.4349803", "0.434891", "0.43478632", "0.43478632", "0.43455395", "0.4344903", "0.43447274", "0.4344153" ]
0.8336627
0
distributeReward adds the reward to the future vesting schedule in proportion to the future vesting staking tokens.
distributeReward добавляет награду в будущий график выплат пропорционально будущим востребованным стейкинг-токенам.
func (va ClawbackVestingAccount) distributeReward(ctx sdk.Context, ak AccountKeeper, bondDenom string, reward sdk.Coins) { now := ctx.BlockTime().Unix() t := va.StartTime firstUnvestedPeriod := 0 unvestedTokens := sdk.ZeroInt() for i, period := range va.VestingPeriods { t += period.Length if t <= now { firstUnvestedPeriod = i + 1 continue } unvestedTokens = unvestedTokens.Add(period.Amount.AmountOf(bondDenom)) } runningTotReward := sdk.NewCoins() runningTotStaking := sdk.ZeroInt() for i := firstUnvestedPeriod; i < len(va.VestingPeriods); i++ { period := va.VestingPeriods[i] runningTotStaking = runningTotStaking.Add(period.Amount.AmountOf(bondDenom)) runningTotRatio := runningTotStaking.ToDec().Quo(unvestedTokens.ToDec()) targetCoins := scaleCoins(reward, runningTotRatio) thisReward := targetCoins.Sub(runningTotReward) runningTotReward = targetCoins period.Amount = period.Amount.Add(thisReward...) va.VestingPeriods[i] = period } va.OriginalVesting = va.OriginalVesting.Add(reward...) ak.SetAccount(ctx, &va) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (_BondedECDSAKeep *BondedECDSAKeepTransactor) DistributeETHReward(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.contract.Transact(opts, \"distributeETHReward\")\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactorSession) DistributeETHReward() (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.DistributeETHReward(&_BondedECDSAKeep.TransactOpts)\n}", "func (_BondedECDSAKeep *BondedECDSAKeepSession) DistributeETHReward() (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.DistributeETHReward(&_BondedECDSAKeep.TransactOpts)\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactor) DistributeERC20Reward(opts *bind.TransactOpts, _tokenAddress common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.contract.Transact(opts, \"distributeERC20Reward\", _tokenAddress, _value)\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactorSession) DistributeERC20Reward(_tokenAddress common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.DistributeERC20Reward(&_BondedECDSAKeep.TransactOpts, _tokenAddress, _value)\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 (_BondedECDSAKeep *BondedECDSAKeepSession) DistributeERC20Reward(_tokenAddress common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.DistributeERC20Reward(&_BondedECDSAKeep.TransactOpts, _tokenAddress, _value)\n}", "func (va ClawbackVestingAccount) postReward(ctx sdk.Context, reward sdk.Coins, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) {\n\t// Find the scheduled amount of vested and unvested staking tokens\n\tbondDenom := sk.BondDenom(ctx)\n\tvested := ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, ctx.BlockTime().Unix()).AmountOf(bondDenom)\n\tunvested := va.OriginalVesting.AmountOf(bondDenom).Sub(vested)\n\n\tif unvested.IsZero() {\n\t\t// no need to adjust the vesting schedule\n\t\treturn\n\t}\n\n\tif vested.IsZero() {\n\t\t// all staked tokens must be unvested\n\t\tva.distributeReward(ctx, ak, bondDenom, reward)\n\t\treturn\n\t}\n\n\t// Find current split of account balance on staking axis\n\tbonded := sk.GetDelegatorBonded(ctx, va.GetAddress())\n\tunbonding := sk.GetDelegatorUnbonding(ctx, va.GetAddress())\n\tdelegated := bonded.Add(unbonding)\n\n\t// discover what has been slashed and remove from delegated amount\n\toldDelegated := va.DelegatedVesting.AmountOf(bondDenom).Add(va.DelegatedFree.AmountOf(bondDenom))\n\tslashed := oldDelegated.Sub(intMin(oldDelegated, delegated))\n\tdelegated = delegated.Sub(intMin(delegated, slashed))\n\n\t// Prefer delegated tokens to be unvested\n\tunvested = intMin(unvested, delegated)\n\tvested = delegated.Sub(unvested)\n\n\t// Compute the unvested amount of reward and add to vesting schedule\n\tif unvested.IsZero() {\n\t\treturn\n\t}\n\tif vested.IsZero() {\n\t\tva.distributeReward(ctx, ak, bondDenom, reward)\n\t\treturn\n\t}\n\tunvestedRatio := unvested.ToDec().QuoTruncate(bonded.ToDec()) // round down\n\tunvestedReward := scaleCoins(reward, unvestedRatio)\n\tva.distributeReward(ctx, ak, bondDenom, unvestedReward)\n}", "func (a Actor) AwardBlockReward(rt vmr.Runtime, params *AwardBlockRewardParams) *adt.EmptyValue {\n\trt.ValidateImmediateCallerIs(builtin.SystemActorAddr)\n\tAssertMsg(rt.CurrentBalance().GreaterThanEqual(params.GasReward),\n\t\t\"actor current balance %v insufficient to pay gas reward %v\", rt.CurrentBalance(), params.GasReward)\n\n\tAssertMsg(params.TicketCount > 0, \"cannot give block reward for zero tickets\")\n\n\tminer, ok := rt.ResolveAddress(params.Miner)\n\tif !ok {\n\t\trt.Abortf(exitcode.ErrIllegalState, \"failed to resolve given owner address\")\n\t}\n\n\tpriorBalance := rt.CurrentBalance()\n\n\tvar penalty abi.TokenAmount\n\tvar st State\n\trt.State().Transaction(&st, func() interface{} {\n\t\tblockReward := a.computeBlockReward(&st, big.Sub(priorBalance, params.GasReward), params.TicketCount)\n\t\ttotalReward := big.Add(blockReward, params.GasReward)\n\n\t\t// Cap the penalty at the total reward value.\n\t\tpenalty = big.Min(params.Penalty, totalReward)\n\n\t\t// Reduce the payable reward by the penalty.\n\t\trewardPayable := big.Sub(totalReward, penalty)\n\n\t\tAssertMsg(big.Add(rewardPayable, penalty).LessThanEqual(priorBalance),\n\t\t\t\"reward payable %v + penalty %v exceeds balance %v\", rewardPayable, penalty, priorBalance)\n\n\t\t// Record new reward into reward map.\n\t\tif rewardPayable.GreaterThan(abi.NewTokenAmount(0)) {\n\t\t\tnewReward := Reward{\n\t\t\t\tStartEpoch: rt.CurrEpoch(),\n\t\t\t\tEndEpoch: rt.CurrEpoch() + rewardVestingPeriod,\n\t\t\t\tValue: rewardPayable,\n\t\t\t\tAmountWithdrawn: abi.NewTokenAmount(0),\n\t\t\t\tVestingFunction: rewardVestingFunction,\n\t\t\t}\n\t\t\tif err := st.addReward(adt.AsStore(rt), miner, &newReward); err != nil {\n\t\t\t\trt.Abortf(exitcode.ErrIllegalState, \"failed to add reward to rewards map: %w\", err)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\n\t// Burn the penalty amount.\n\t_, code := rt.Send(builtin.BurntFundsActorAddr, builtin.MethodSend, nil, penalty)\n\tbuiltin.RequireSuccess(rt, code, \"failed to send penalty to BurntFundsActor\")\n\n\treturn nil\n}", "func (s *MutableState) AddRewards(time epochtime.EpochTime, factor *quantity.Quantity, accounts []signature.PublicKey) error {\n\tsteps, err := s.RewardSchedule()\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar activeStep *staking.RewardStep\n\tfor _, step := range steps {\n\t\tif time < step.Until {\n\t\t\tactiveStep = &step\n\t\t\tbreak\n\t\t}\n\t}\n\tif activeStep == nil {\n\t\t// We're past the end of the schedule.\n\t\treturn nil\n\t}\n\n\tcommonPool, err := s.CommonPool()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"loading common pool\")\n\t}\n\n\tfor _, id := range accounts {\n\t\tent := s.Account(id)\n\n\t\tq := ent.Escrow.Active.Balance.Clone()\n\t\t// Multiply first.\n\t\tif err := q.Mul(factor); err != nil {\n\t\t\treturn errors.Wrap(err, \"multiplying by reward factor\")\n\t\t}\n\t\tif err := q.Mul(&activeStep.Scale); err != nil {\n\t\t\treturn errors.Wrap(err, \"multiplying by reward step scale\")\n\t\t}\n\t\tif err := q.Quo(staking.RewardAmountDenominator); err != nil {\n\t\t\treturn errors.Wrap(err, \"dividing by reward amount denominator\")\n\t\t}\n\n\t\tif q.IsZero() {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar com *quantity.Quantity\n\t\trate := ent.Escrow.CommissionSchedule.CurrentRate(time)\n\t\tif rate != nil {\n\t\t\tcom = q.Clone()\n\t\t\t// Multiply first.\n\t\t\tif err := com.Mul(rate); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"multiplying by commission rate\")\n\t\t\t}\n\t\t\tif err := com.Quo(staking.CommissionRateDenominator); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"dividing by commission rate denominator\")\n\t\t\t}\n\n\t\t\tif err := q.Sub(com); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"subtracting commission\")\n\t\t\t}\n\t\t}\n\n\t\tif !q.IsZero() {\n\t\t\tif err := quantity.Move(&ent.Escrow.Active.Balance, commonPool, q); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"transferring to active escrow balance from common pool\")\n\t\t\t}\n\t\t}\n\n\t\tif com != nil && !com.IsZero() {\n\t\t\tdelegation := s.Delegation(id, id)\n\n\t\t\tif err := ent.Escrow.Active.Deposit(&delegation.Shares, commonPool, com); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"depositing commission\")\n\t\t\t}\n\n\t\t\ts.SetDelegation(id, id, delegation)\n\t\t}\n\n\t\ts.SetAccount(id, ent)\n\t}\n\n\ts.SetCommonPool(commonPool)\n\n\treturn nil\n}", "func (s *MutableState) AddRewardSingleAttenuated(time epochtime.EpochTime, factor *quantity.Quantity, attenuationNumerator, attenuationDenominator int, account signature.PublicKey) error {\n\tsteps, err := s.RewardSchedule()\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar activeStep *staking.RewardStep\n\tfor _, step := range steps {\n\t\tif time < step.Until {\n\t\t\tactiveStep = &step\n\t\t\tbreak\n\t\t}\n\t}\n\tif activeStep == nil {\n\t\t// We're past the end of the schedule.\n\t\treturn nil\n\t}\n\n\tvar numQ, denQ quantity.Quantity\n\tif err = numQ.FromInt64(int64(attenuationNumerator)); err != nil {\n\t\treturn errors.Wrapf(err, \"importing attenuation numerator %d\", attenuationNumerator)\n\t}\n\tif err = denQ.FromInt64(int64(attenuationDenominator)); err != nil {\n\t\treturn errors.Wrapf(err, \"importing attenuation denominator %d\", attenuationDenominator)\n\t}\n\n\tcommonPool, err := s.CommonPool()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"loading common pool\")\n\t}\n\n\tent := s.Account(account)\n\n\tq := ent.Escrow.Active.Balance.Clone()\n\t// Multiply first.\n\tif err := q.Mul(factor); err != nil {\n\t\treturn errors.Wrap(err, \"multiplying by reward factor\")\n\t}\n\tif err := q.Mul(&activeStep.Scale); err != nil {\n\t\treturn errors.Wrap(err, \"multiplying by reward step scale\")\n\t}\n\tif err := q.Mul(&numQ); err != nil {\n\t\treturn errors.Wrap(err, \"multiplying by attenuation numerator\")\n\t}\n\tif err := q.Quo(staking.RewardAmountDenominator); err != nil {\n\t\treturn errors.Wrap(err, \"dividing by reward amount denominator\")\n\t}\n\tif err := q.Quo(&denQ); err != nil {\n\t\treturn errors.Wrap(err, \"dividing by attenuation denominator\")\n\t}\n\n\tif q.IsZero() {\n\t\treturn nil\n\t}\n\n\tvar com *quantity.Quantity\n\trate := ent.Escrow.CommissionSchedule.CurrentRate(time)\n\tif rate != nil {\n\t\tcom = q.Clone()\n\t\t// Multiply first.\n\t\tif err := com.Mul(rate); err != nil {\n\t\t\treturn errors.Wrap(err, \"multiplying by commission rate\")\n\t\t}\n\t\tif err := com.Quo(staking.CommissionRateDenominator); err != nil {\n\t\t\treturn errors.Wrap(err, \"dividing by commission rate denominator\")\n\t\t}\n\n\t\tif err := q.Sub(com); err != nil {\n\t\t\treturn errors.Wrap(err, \"subtracting commission\")\n\t\t}\n\t}\n\n\tif !q.IsZero() {\n\t\tif err := quantity.Move(&ent.Escrow.Active.Balance, commonPool, q); err != nil {\n\t\t\treturn errors.Wrap(err, \"transferring to active escrow balance from common pool\")\n\t\t}\n\t}\n\n\tif com != nil && !com.IsZero() {\n\t\tdelegation := s.Delegation(account, account)\n\n\t\tif err := ent.Escrow.Active.Deposit(&delegation.Shares, commonPool, com); err != nil {\n\t\t\treturn errors.Wrap(err, \"depositing commission\")\n\t\t}\n\n\t\ts.SetDelegation(account, account, delegation)\n\t}\n\n\ts.SetAccount(account, ent)\n\n\ts.SetCommonPool(commonPool)\n\n\treturn nil\n}", "func weighted_reward(w map[int]float64, allocation vrp.Allocation) float64 {\n\tvar reward float64\n\tfor id, _ := range allocation {\n\t\treward += w[id] * allocation[id]\n\t}\n\treturn reward\n}", "func (d *Dao) AddReward(c context.Context, iRewardID int64, uid int64, iSource int64, iRoomid int64, iLifespan int64) (err error) {\n\t//aReward, _ := getRewardConfByLid(iRewardID)\n\n\tm, _ := time.ParseDuration(fmt.Sprintf(\"+%dh\", iLifespan))\n\n\targ := &AnchorTaskModel.AnchorReward{\n\t\tUid: uid,\n\t\tRewardId: iRewardID,\n\t\tRoomid: iRoomid,\n\t\tSource: iSource,\n\t\tAchieveTime: xtime.Time(time.Now().Unix()),\n\t\tExpireTime: xtime.Time(time.Now().Add(m).Unix()),\n\t\tStatus: model.RewardUnUsed,\n\t}\n\n\t//spew.Dump\n\t// (arg)\n\tif err := d.orm.Create(arg).Error; err != nil {\n\t\tlog.Error(\"addReward(%v) error(%v)\", arg, err)\n\t\treturn err\n\t}\n\n\tif err := d.SetNewReward(c, uid, int64(1)); err != nil {\n\t\tlog.Error(\"addRewardMc(%v) error(%v)\", uid, err)\n\t}\n\n\tif err := d.SetHasReward(c, uid, int64(1)); err != nil {\n\t\tlog.Error(\"SetHasReward(%v) error(%v)\", uid, err)\n\t}\n\n\tlog.Info(\"addReward (%v) succ\", arg)\n\n\treturn\n}", "func (_XStaking *XStakingCaller) RewardsDistribution(opts *bind.CallOpts) (common.Address, error) {\n\tvar out []interface{}\n\terr := _XStaking.contract.Call(opts, &out, \"rewardsDistribution\")\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 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 (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 accumulateRewards(config *params.ChainConfig, state *state.DB, header *types.Header) {\n\t// TODO: implement mining rewards\n}", "func EstimateReward(reward, pr, gamma float64) float64 {\n\tret := reward / (pr + gamma)\n\tlog.Logf(MABLogLevel, \"MAB Estimate Reward: %v / (%v + %v) = %v\\n\",\n\t\treward, pr, gamma, ret)\n\treturn ret\n}", "func rewardAndSlash(ctx contract.Context, cachedDelegations *CachedDposStorage, state *State) ([]*DelegationResult, error) {\n\tformerValidatorTotals := make(map[string]loom.BigUInt)\n\tdelegatorRewards := make(map[string]*loom.BigUInt)\n\tdistributedRewards := common.BigZero()\n\n\tdelegations, err := cachedDelegations.loadDelegationList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, validator := range state.Validators {\n\t\tcandidate := GetCandidateByPubKey(ctx, validator.PubKey)\n\n\t\tif candidate == nil {\n\t\t\tctx.Logger().Info(\"Attempted to reward validator no longer on candidates list.\", \"validator\", validator)\n\t\t\tcontinue\n\t\t}\n\n\t\tcandidateAddress := loom.UnmarshalAddressPB(candidate.Address)\n\t\tvalidatorKey := candidateAddress.String()\n\t\tstatistic, _ := GetStatistic(ctx, candidateAddress)\n\n\t\tif statistic == nil {\n\t\t\tdelegatorRewards[validatorKey] = common.BigZero()\n\t\t\tformerValidatorTotals[validatorKey] = *common.BigZero()\n\t\t} else {\n\t\t\t// If a validator is jailed, don't calculate and distribute rewards\n\t\t\tif ctx.FeatureEnabled(features.DPOSVersion3_3, false) {\n\t\t\t\tif statistic.Jailed {\n\t\t\t\t\tdelegatorRewards[validatorKey] = common.BigZero()\n\t\t\t\t\tformerValidatorTotals[validatorKey] = *common.BigZero()\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\t// If a validator's SlashPercentage is 0, the validator is\n\t\t\t// rewarded for avoiding faults during the last slashing period\n\t\t\tif common.IsZero(statistic.SlashPercentage.Value) {\n\t\t\t\tdistributionTotal := calculateRewards(statistic.DelegationTotal.Value, state.Params, state.TotalValidatorDelegations.Value)\n\n\t\t\t\t// The validator share, equal to validator_fee * total_validotor_reward\n\t\t\t\t// is to be split between the referrers and the validator\n\t\t\t\tvalidatorShare := CalculateFraction(loom.BigUInt{big.NewInt(int64(candidate.Fee))}, distributionTotal)\n\n\t\t\t\t// delegatorsShare is what fraction of the total rewards will be\n\t\t\t\t// distributed to delegators\n\t\t\t\tdelegatorsShare := common.BigZero()\n\t\t\t\tdelegatorsShare.Sub(&distributionTotal, &validatorShare)\n\t\t\t\tdelegatorRewards[validatorKey] = delegatorsShare\n\n\t\t\t\t// Distribute rewards to referrers\n\t\t\t\tfor _, d := range delegations {\n\t\t\t\t\tif loom.UnmarshalAddressPB(d.Validator).Compare(loom.UnmarshalAddressPB(candidate.Address)) == 0 {\n\t\t\t\t\t\tdelegation, err := GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\t\t\t\t\t// if the delegation is not found OR if the delegation\n\t\t\t\t\t\t// has no referrer, we do not need to attempt to\n\t\t\t\t\t\t// distribute the referrer rewards\n\t\t\t\t\t\tif err == contract.ErrNotFound || len(delegation.Referrer) == 0 {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t} else if err != nil {\n\t\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// if referrer is not found, do not distribute the reward\n\t\t\t\t\t\treferrerAddress := getReferrer(ctx, delegation.Referrer)\n\t\t\t\t\t\tif referrerAddress == nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// calculate referrerReward\n\t\t\t\t\t\treferrerReward := calculateRewards(delegation.Amount.Value, state.Params, state.TotalValidatorDelegations.Value)\n\t\t\t\t\t\treferrerReward = CalculateFraction(loom.BigUInt{big.NewInt(int64(candidate.Fee))}, referrerReward)\n\t\t\t\t\t\treferrerReward = CalculateFraction(defaultReferrerFee, referrerReward)\n\n\t\t\t\t\t\t// referrer fees are delegater to limbo validator\n\t\t\t\t\t\tdistributedRewards.Add(distributedRewards, &referrerReward)\n\t\t\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, LimboValidatorAddress(ctx).MarshalPB(), referrerAddress, referrerReward)\n\n\t\t\t\t\t\t// any referrer bonus amount is subtracted from the validatorShare\n\t\t\t\t\t\tvalidatorShare.Sub(&validatorShare, &referrerReward)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tdistributedRewards.Add(distributedRewards, &validatorShare)\n\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, candidate.Address, candidate.Address, validatorShare)\n\n\t\t\t\t// If a validator has some non-zero WhitelistAmount,\n\t\t\t\t// calculate the validator's reward based on whitelist amount\n\t\t\t\tif !common.IsZero(statistic.WhitelistAmount.Value) {\n\t\t\t\t\tamount := calculateWeightedWhitelistAmount(*statistic)\n\t\t\t\t\twhitelistDistribution := calculateShare(amount, statistic.DelegationTotal.Value, *delegatorsShare)\n\t\t\t\t\t// increase a delegator's distribution\n\t\t\t\t\tdistributedRewards.Add(distributedRewards, &whitelistDistribution)\n\t\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, candidate.Address, candidate.Address, whitelistDistribution)\n\t\t\t\t}\n\n\t\t\t\t// Keeping track of cumulative distributed rewards by adding\n\t\t\t\t// every validator's total rewards to\n\t\t\t\t// `state.TotalRewardDistribution`\n\t\t\t\t// NOTE: because we round down in every `calculateRewards` call,\n\t\t\t\t// we expect `state.TotalRewardDistribution` to be a slight\n\t\t\t\t// overestimate of what was actually distributed. We could be\n\t\t\t\t// exact with our record keeping by incrementing\n\t\t\t\t// `state.TotalRewardDistribution` each time\n\t\t\t\t// `IncreaseRewardDelegation` is called, but because we will not\n\t\t\t\t// use `state.TotalRewardDistributions` as part of any invariants,\n\t\t\t\t// we will live with this situation.\n\t\t\t\tif !ctx.FeatureEnabled(features.DPOSVersion3_1, false) {\n\t\t\t\t\tstate.TotalRewardDistribution.Value.Add(&state.TotalRewardDistribution.Value, &distributionTotal)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif err := slashValidatorDelegations(ctx, cachedDelegations, statistic, candidateAddress); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tif err := SetStatistic(ctx, statistic); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tformerValidatorTotals[validatorKey] = statistic.DelegationTotal.Value\n\t\t}\n\t}\n\n\tnewDelegationTotals, err := distributeDelegatorRewards(ctx, cachedDelegations, formerValidatorTotals, delegatorRewards, distributedRewards)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif ctx.FeatureEnabled(features.DPOSVersion3_1, false) {\n\t\tstate.TotalRewardDistribution.Value.Add(&state.TotalRewardDistribution.Value, distributedRewards)\n\t}\n\n\tdelegationResults := make([]*DelegationResult, 0, len(newDelegationTotals))\n\tfor validator := range newDelegationTotals {\n\t\tdelegationResults = append(delegationResults, &DelegationResult{\n\t\t\tValidatorAddress: loom.MustParseAddress(validator),\n\t\t\tDelegationTotal: *newDelegationTotals[validator],\n\t\t})\n\t}\n\tsort.Sort(byDelegationTotal(delegationResults))\n\n\treturn delegationResults, nil\n}", "func (node *TreeNode) backpropagateReward(scores [2]float64) {\n\tcurrentNode := node\n\tfor currentNode.Parent != nil {\n\t\tcurrentNode.VisitCount += 1.0\n\t\tcurrentNode.CumulativeScore[0] += scores[0]\n\t\tcurrentNode.CumulativeScore[1] += scores[1]\n\t\tcurrentNode = currentNode.Parent\n\t}\n\t//Increment root node counter\n\tcurrentNode.VisitCount += 1.0\n}", "func (k Keeper) ClaimEarnReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tsyncedClaim, found := k.GetSynchronizedEarnClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr := k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetEarnClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func computeReward(epoch abi.ChainEpoch, prevTheta, currTheta, simpleTotal, baselineTotal big.Int) abi.TokenAmount {\n\tsimpleReward := big.Mul(simpleTotal, ExpLamSubOne) //Q.0 * Q.128 => Q.128\n\tepochLam := big.Mul(big.NewInt(int64(epoch)), Lambda) // Q.0 * Q.128 => Q.128\n\n\tsimpleReward = big.Mul(simpleReward, big.NewFromGo(math.ExpNeg(epochLam.Int))) // Q.128 * Q.128 => Q.256\n\tsimpleReward = big.Rsh(simpleReward, math.Precision128) // Q.256 >> 128 => Q.128\n\n\tbaselineReward := big.Sub(computeBaselineSupply(currTheta, baselineTotal), computeBaselineSupply(prevTheta, baselineTotal)) // Q.128\n\n\treward := big.Add(simpleReward, baselineReward) // Q.128\n\n\treturn big.Rsh(reward, math.Precision128) // Q.128 => Q.0\n}", "func ApplyRewardTx(tx *types.Transaction, statedb *state.Statedb) (*types.Receipt, error) {\n\tstatedb.CreateAccount(tx.Data.To)\n\tstatedb.AddBalance(tx.Data.To, tx.Data.Amount)\n\n\thash, err := statedb.Hash()\n\tif err != nil {\n\t\treturn nil, errors.NewStackedError(err, \"failed to get statedb root hash\")\n\t}\n\n\treceipt := &types.Receipt{\n\t\tTxHash: tx.Hash,\n\t\tPostState: hash,\n\t}\n\n\treturn receipt, nil\n}", "func (_RewardsDistributionRecipient *RewardsDistributionRecipientSession) NotifyRewardAmount(reward *big.Int) (*types.Transaction, error) {\n\treturn _RewardsDistributionRecipient.Contract.NotifyRewardAmount(&_RewardsDistributionRecipient.TransactOpts, reward)\n}", "func (_RewardsDistributionRecipient *RewardsDistributionRecipientTransactorSession) NotifyRewardAmount(reward *big.Int) (*types.Transaction, error) {\n\treturn _RewardsDistributionRecipient.Contract.NotifyRewardAmount(&_RewardsDistributionRecipient.TransactOpts, reward)\n}", "func (e *engineImpl) Rewarder() reward.Distributor {\n\treturn e.d\n}", "func (_XStaking *XStakingSession) RewardsDistribution() (common.Address, error) {\n\treturn _XStaking.Contract.RewardsDistribution(&_XStaking.CallOpts)\n}", "func (_XStaking *XStakingTransactor) SetRewardsDistribution(opts *bind.TransactOpts, _rewardsDistribution common.Address) (*types.Transaction, error) {\n\treturn _XStaking.contract.Transact(opts, \"setRewardsDistribution\", _rewardsDistribution)\n}", "func (_RewardsDistributionRecipient *RewardsDistributionRecipientCaller) RewardsDistribution(opts *bind.CallOpts) (common.Address, error) {\n\tvar out []interface{}\n\terr := _RewardsDistributionRecipient.contract.Call(opts, &out, \"rewardsDistribution\")\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 (_RandomBeacon *RandomBeaconTransactor) UpdateRewardParameters(opts *bind.TransactOpts, sortitionPoolRewardsBanDuration *big.Int, relayEntryTimeoutNotificationRewardMultiplier *big.Int, unauthorizedSigningNotificationRewardMultiplier *big.Int, dkgMaliciousResultNotificationRewardMultiplier *big.Int) (*types.Transaction, error) {\n\treturn _RandomBeacon.contract.Transact(opts, \"updateRewardParameters\", sortitionPoolRewardsBanDuration, relayEntryTimeoutNotificationRewardMultiplier, unauthorizedSigningNotificationRewardMultiplier, dkgMaliciousResultNotificationRewardMultiplier)\n}", "func (k Keeper) AllocateTokens(ctx sdk.Context, percentVotes sdk.Dec, proposer sdk.ConsAddress) {\n\tlogger := ctx.Logger()\n\t// get the proposer of this block\n\tproposerValidator := k.stakeKeeper.ValidatorByConsAddr(ctx, proposer)\n\n\tif proposerValidator == nil {\n\t\tpanic(fmt.Sprintf(\"Can't find proposer %s in validator set\", proposerValidator.GetConsAddr()))\n\t}\n\n\tproposerDist := k.GetValidatorDistInfo(ctx, proposerValidator.GetOperator())\n\n\t// get the fees which have been getting collected through all the\n\t// transactions in the block\n\tfeesCollected := k.feeKeeper.GetCollectedFees(ctx)\n\tfeesCollectedDec := types.NewDecCoins(feesCollected)\n\n\tlogger.Info(\"Get collected transaction fee token and minted token\", \"collected_token\", feesCollected)\n\n\tfeePool := k.GetFeePool(ctx)\n\tif k.stakeKeeper.GetLastTotalPower(ctx).IsZero() {\n\t\tk.bankKeeper.AddCoins(ctx, auth.CommunityTaxCoinsAccAddr, feesCollected)\n\t\t//\t\tfeePool.CommunityPool = feePool.CommunityPool.Add(feesCollectedDec)\n\t\t//\t\tk.SetFeePool(ctx, feePool)\n\t\tk.feeKeeper.ClearCollectedFees(ctx)\n\t\tctx.CoinFlowTags().AppendCoinFlowTag(ctx, \"\", auth.CommunityTaxCoinsAccAddr.String(), feesCollected.String(), sdk.CommunityTaxCollectFlow, \"\")\n\t\treturn\n\t}\n\n\tvar proposerReward types.DecCoins\n\t// If a validator is jailed, distribute no reward to it\n\t// The jailed validator happen to be a proposer which is a very corner case\n\tvalidator := k.stakeKeeper.Validator(ctx, proposerValidator.GetOperator())\n\tif !validator.GetJailed() {\n\t\t// allocated rewards to proposer\n\t\tlogger.Info(\"Allocate reward to proposer\", \"proposer_address\", proposerValidator.GetOperator().String())\n\t\tbaseProposerReward := k.GetBaseProposerReward(ctx)\n\t\tbonusProposerReward := k.GetBonusProposerReward(ctx)\n\t\tproposerMultiplier := baseProposerReward.Add(bonusProposerReward.Mul(percentVotes))\n\t\tproposerReward = feesCollectedDec.MulDec(proposerMultiplier)\n\n\t\t// apply commission\n\t\tcommission := proposerReward.MulDec(proposerValidator.GetCommission())\n\t\tremaining := proposerReward.Minus(commission)\n\t\tproposerDist.ValCommission = proposerDist.ValCommission.Plus(commission)\n\t\tproposerDist.DelPool = proposerDist.DelPool.Plus(remaining)\n\t\tlogger.Info(\"Allocate commission to proposer commission pool\", \"commission\", commission.ToString())\n\t\tlogger.Info(\"Allocate reward to proposer delegation reward pool\", \"delegation_reward\", remaining.ToString())\n\n\t\t// save validator distribution info\n\t\tk.SetValidatorDistInfo(ctx, proposerDist)\n\t} else {\n\t\tlogger.Info(\"The block proposer is jailed, distribute no reward to it\", \"proposer_address\", proposerValidator.GetOperator().String())\n\t}\n\n\t// allocate community funding\n\tcommunityTax := k.GetCommunityTax(ctx)\n\tcommunityFunding := feesCollectedDec.MulDec(communityTax)\n\n\t//\tfeePool.CommunityPool = feePool.CommunityPool.Add(communityFunding)\n\tfundingCoins, change := communityFunding.TruncateDecimal()\n\tk.bankKeeper.AddCoins(ctx, auth.CommunityTaxCoinsAccAddr, fundingCoins)\n\tctx.CoinFlowTags().AppendCoinFlowTag(ctx, \"\", auth.CommunityTaxCoinsAccAddr.String(), fundingCoins.String(), sdk.CommunityTaxCollectFlow, \"\")\n\n\tcommunityTaxCoins := k.bankKeeper.GetCoins(ctx, auth.CommunityTaxCoinsAccAddr)\n\tcommunityTaxDec := sdk.NewDecFromInt(communityTaxCoins.AmountOf(sdk.IrisAtto))\n\tcommunityTaxFloat, err := strconv.ParseFloat(communityTaxDec.QuoInt(sdk.AttoScaleFactor).String(), 64)\n\t//communityTaxAmount, err := strconv.ParseFloat(feePool.CommunityPool.AmountOf(sdk.IrisAtto).QuoInt(sdk.AttoScaleFactor).String(), 64)\n\tif err == nil {\n\t\tk.metrics.CommunityTax.Set(communityTaxFloat)\n\t}\n\n\tlogger.Info(\"Allocate reward to community tax fund\", \"allocate_amount\", fundingCoins.String(), \"total_community_tax\", communityTaxCoins.String())\n\n\t// set the global pool within the distribution module\n\tpoolReceived := feesCollectedDec.Minus(proposerReward).Minus(communityFunding).Plus(change)\n\tfeePool.ValPool = feePool.ValPool.Plus(poolReceived)\n\tk.SetFeePool(ctx, feePool)\n\n\tlogger.Info(\"Allocate reward to global validator pool\", \"allocate_amount\", poolReceived.ToString(), \"total_global_validator_pool\", feePool.ValPool.ToString())\n\n\t// clear the now distributed fees\n\tk.feeKeeper.ClearCollectedFees(ctx)\n}", "func (_XStaking *XStakingSession) SetRewardsDistribution(_rewardsDistribution common.Address) (*types.Transaction, error) {\n\treturn _XStaking.Contract.SetRewardsDistribution(&_XStaking.TransactOpts, _rewardsDistribution)\n}", "func (_XStaking *XStakingTransactorSession) SetRewardsDistribution(_rewardsDistribution common.Address) (*types.Transaction, error) {\n\treturn _XStaking.Contract.SetRewardsDistribution(&_XStaking.TransactOpts, _rewardsDistribution)\n}", "func (_RewardsDistributionRecipient *RewardsDistributionRecipientTransactor) NotifyRewardAmount(opts *bind.TransactOpts, reward *big.Int) (*types.Transaction, error) {\n\treturn _RewardsDistributionRecipient.contract.Transact(opts, \"notifyRewardAmount\", reward)\n}", "func (t *trusteeImpl) NewMiningRewardTx(block consensus.Block) *consensus.Transaction {\n\tvar tx *consensus.Transaction\n\t// build list of miner nodes for uncle blocks\n\tuncleMiners := make([][]byte, len(block.UncleMiners()))\n\tfor i, uncleMiner := range block.UncleMiners() {\n\t\tuncleMiners[i] = uncleMiner\n\t}\n\t\n\tops := make([]Op, 1 + len(uncleMiners))\n\t// first add self's mining reward\n\tops[0] = *t.myReward\n\t\n\t// now add award for each uncle\n\tfor i, uncleMiner := range uncleMiners {\n\t\top := NewOp(OpReward)\n\t\top.Params[ParamUncle] = bytesToHexString(uncleMiner)\n\t\top.Params[ParamAward] = UncleAward\n\t\tops[i+1] = *op \n\t}\n\t// serialize ops into payload\n\tif payload,err := common.Serialize(ops); err != nil {\n\t\tt.log.Error(\"Failed to serialize ops into payload: %s\", err)\n\t\treturn nil\n\t} else {\n\t\t// make a signed transaction out of payload\n\t\tif signature := t.sign(payload); len(signature) > 0 {\n\t\t\t// return the signed transaction\n\t\t\ttx = consensus.NewTransaction(payload, signature, t.myAddress)\n\t\t\tblock.AddTransaction(tx)\n\t\t\tt.process(block, tx)\n\t\t}\n\t}\n\treturn tx\n}", "func (k Querier) Rewards(c context.Context, req *types.QueryRewardsRequest) (*types.QueryRewardsResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"invalid request\")\n\t}\n\n\tif req.StakingCoinDenom != \"\" {\n\t\tif err := sdk.ValidateDenom(req.StakingCoinDenom); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tctx := sdk.UnwrapSDKContext(c)\n\tstore := ctx.KVStore(k.storeKey)\n\tvar rewards []types.Reward\n\tvar pageRes *query.PageResponse\n\tvar err error\n\n\tif req.Farmer != \"\" {\n\t\tvar farmerAcc sdk.AccAddress\n\t\tfarmerAcc, err = sdk.AccAddressFromBech32(req.Farmer)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tstorePrefix := types.GetRewardsByFarmerIndexKey(farmerAcc)\n\t\tindexStore := prefix.NewStore(store, storePrefix)\n\t\tpageRes, err = query.FilteredPaginate(indexStore, req.Pagination, func(key, value []byte, accumulate bool) (bool, error) {\n\t\t\t_, stakingCoinDenom := types.ParseRewardsByFarmerIndexKey(append(storePrefix, key...))\n\t\t\tif req.StakingCoinDenom != \"\" {\n\t\t\t\tif stakingCoinDenom != req.StakingCoinDenom {\n\t\t\t\t\treturn false, nil\n\t\t\t\t}\n\t\t\t}\n\t\t\treward, found := k.GetReward(ctx, stakingCoinDenom, farmerAcc)\n\t\t\tif !found { // TODO: remove this check\n\t\t\t\treturn false, fmt.Errorf(\"reward not found\")\n\t\t\t}\n\t\t\tif accumulate {\n\t\t\t\trewards = append(rewards, reward)\n\t\t\t}\n\t\t\treturn true, nil\n\t\t})\n\t} else {\n\t\tvar storePrefix []byte\n\t\tif req.StakingCoinDenom != \"\" {\n\t\t\tstorePrefix = types.GetRewardsByStakingCoinDenomKey(req.StakingCoinDenom)\n\t\t} else {\n\t\t\tstorePrefix = types.RewardKeyPrefix\n\t\t}\n\t\trewardStore := prefix.NewStore(store, storePrefix)\n\n\t\tpageRes, err = query.Paginate(rewardStore, req.Pagination, func(key, value []byte) error {\n\t\t\tstakingCoinDenom, farmerAcc := types.ParseRewardKey(append(storePrefix, key...))\n\t\t\trewardCoins, err := k.UnmarshalRewardCoins(value)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\trewards = append(rewards, types.Reward{\n\t\t\t\tFarmer: farmerAcc.String(),\n\t\t\t\tStakingCoinDenom: stakingCoinDenom,\n\t\t\t\tRewardCoins: rewardCoins.RewardCoins,\n\t\t\t})\n\t\t\treturn nil\n\t\t})\n\t}\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &types.QueryRewardsResponse{Rewards: rewards, Pagination: pageRes}, nil\n}", "func (path *Path) AddRewards(rewards map[*Reward]int) {\n\tfor key, value := range rewards {\n\t\tpath.rewards[key] += value\n\t}\n}", "func rewardRate(pool sdk.Coins, blocks int64) sdk.Coins {\n\tcoins := make([]sdk.Coin, 0)\n\tif blocks > 0 {\n\t\tfor _, coin := range pool {\n\t\t\tif coin.IsZero() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// divide by blocks, rounding fractions up\n\t\t\t// (coin.Amount - 1)/blocks + 1\n\t\t\trate := coin.Amount.SubRaw(1).QuoRaw(blocks).AddRaw(1)\n\t\t\tcoins = append(coins, sdk.NewCoin(coin.GetDenom(), rate))\n\t\t}\n\t}\n\treturn sdk.NewCoins(coins...)\n}", "func (_XStaking *XStakingCallerSession) RewardsDistribution() (common.Address, error) {\n\treturn _XStaking.Contract.RewardsDistribution(&_XStaking.CallOpts)\n}", "func (_RandomBeacon *RandomBeaconTransactorSession) UpdateRewardParameters(sortitionPoolRewardsBanDuration *big.Int, relayEntryTimeoutNotificationRewardMultiplier *big.Int, unauthorizedSigningNotificationRewardMultiplier *big.Int, dkgMaliciousResultNotificationRewardMultiplier *big.Int) (*types.Transaction, error) {\n\treturn _RandomBeacon.Contract.UpdateRewardParameters(&_RandomBeacon.TransactOpts, sortitionPoolRewardsBanDuration, relayEntryTimeoutNotificationRewardMultiplier, unauthorizedSigningNotificationRewardMultiplier, dkgMaliciousResultNotificationRewardMultiplier)\n}", "func (k Keeper) ClaimSwapReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tsyncedClaim, found := k.GetSynchronizedSwapClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr := k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetSwapClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func (_RandomBeacon *RandomBeaconSession) UpdateRewardParameters(sortitionPoolRewardsBanDuration *big.Int, relayEntryTimeoutNotificationRewardMultiplier *big.Int, unauthorizedSigningNotificationRewardMultiplier *big.Int, dkgMaliciousResultNotificationRewardMultiplier *big.Int) (*types.Transaction, error) {\n\treturn _RandomBeacon.Contract.UpdateRewardParameters(&_RandomBeacon.TransactOpts, sortitionPoolRewardsBanDuration, relayEntryTimeoutNotificationRewardMultiplier, unauthorizedSigningNotificationRewardMultiplier, dkgMaliciousResultNotificationRewardMultiplier)\n}", "func (k Keeper) ClaimSavingsReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tk.SynchronizeSavingsClaim(ctx, owner)\n\n\tsyncedClaim, found := k.GetSavingsClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr := k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetSavingsClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func (c *Calculator) votingReward(\n\tmultiplier *big.Int,\n\tdivider *big.Int,\n\tfrom int,\n\tto int,\n\tprepInfo map[string]*pRepEnable,\n\titer icstate.VotingIterator,\n) *big.Int {\n\ttotal := new(big.Int)\n\tcheckMinVoting := c.global.GetIISSVersion() == icstate.IISSVersion2\n\tfor ; iter.Has(); iter.Next() {\n\t\tif voting, err := iter.Get(); err != nil {\n\t\t\tc.log.Errorf(\"Failed to iterate votings err=%+v\", err)\n\t\t} else {\n\t\t\tif checkMinVoting && voting.Amount().Cmp(BigIntMinDelegation) < 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ts := from\n\t\t\te := to\n\t\t\tif prep, ok := prepInfo[icutils.ToKey(voting.To())]; ok {\n\t\t\t\tif prep.StartOffset() != 0 && prep.StartOffset() > s {\n\t\t\t\t\ts = prep.StartOffset()\n\t\t\t\t}\n\t\t\t\tif prep.EndOffset() != 0 && prep.EndOffset() < e {\n\t\t\t\t\te = prep.EndOffset()\n\t\t\t\t}\n\t\t\t\tperiod := e - s\n\t\t\t\tif period <= 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\treward := new(big.Int).Mul(multiplier, voting.Amount())\n\t\t\t\treward.Mul(reward, big.NewInt(int64(period)))\n\t\t\t\treward.Div(reward, divider)\n\t\t\t\ttotal.Add(total, reward)\n\t\t\t\tc.log.Tracef(\"VotingReward %s: %s = %s * %s * %d / %s\",\n\t\t\t\t\tvoting.To(), reward, multiplier, voting.Amount(), period, divider)\n\t\t\t}\n\t\t}\n\t}\n\treturn total\n}", "func (c *Coinbase) AddReward(output *Output) {\n\toutput.EncryptedMask = make([]byte, 1)\n\tc.Rewards = append(c.Rewards, output)\n}", "func (d *RandomWalkDistribution) Advance() {\n\td.Step.Advance()\n\td.State += d.Step.Get()\n}", "func MakeReweigh(db *pop.Connection, assertions Assertions) models.Reweigh {\n\tshipment := assertions.MTOShipment\n\tif isZeroUUID(shipment.ID) {\n\t\tassertions.MTOShipment.Status = models.MTOShipmentStatusApproved\n\t\tshipment = MakeMTOShipment(db, assertions)\n\t}\n\n\treweigh := models.Reweigh{\n\t\tRequestedAt: time.Now(),\n\t\tRequestedBy: models.ReweighRequesterTOO,\n\t\tShipment: shipment,\n\t\tShipmentID: shipment.ID,\n\t}\n\n\tmergeModels(&reweigh, assertions.Reweigh)\n\n\tmustCreate(db, &reweigh, assertions.Stub)\n\n\treturn reweigh\n}", "func (ant *Ant) spreadFerment() {\n\tdistance := ant.GetPassedDistance()\n\tdelta := tripWeight / distance\n\tfor i := 0; i < len(ant.visited)-1; i++ {\n\t\tcurrentCity := ant.visited[i]\n\t\tnextCity := ant.visited[i+1]\n\t\toldFerment := (currentCity.Neighbours()[nextCity]).Ferment\n\n\t\t(currentCity.Neighbours()[nextCity]).Ferment = oldFerment*forgetCoefficient + delta\n\t\t(nextCity.Neighbours()[currentCity]).Ferment = oldFerment*forgetCoefficient + delta\n\t}\n}", "func calculateRewards(delegationTotal loom.BigUInt, params *Params, totalValidatorDelegations loom.BigUInt) loom.BigUInt {\n\tcycleSeconds := params.ElectionCycleLength\n\treward := CalculateFraction(blockRewardPercentage, delegationTotal)\n\n\t// If totalValidator Delegations are high enough to make simple reward\n\t// calculations result in more rewards given out than the value of `MaxYearlyReward`,\n\t// scale the rewards appropriately\n\tyearlyRewardTotal := CalculateFraction(blockRewardPercentage, totalValidatorDelegations)\n\tif yearlyRewardTotal.Cmp(&params.MaxYearlyReward.Value) > 0 {\n\t\treward.Mul(&reward, &params.MaxYearlyReward.Value)\n\t\treward.Div(&reward, &yearlyRewardTotal)\n\t}\n\n\t// When election cycle = 0, estimate block time at 2 sec\n\tif cycleSeconds == 0 {\n\t\tcycleSeconds = 2\n\t}\n\treward.Mul(&reward, &loom.BigUInt{big.NewInt(cycleSeconds)})\n\treward.Div(&reward, &secondsInYear)\n\n\treturn reward\n}", "func getRewardForValidator(totalPower *big.Int, validatorPower *big.Int, totalRewards *balance.Amount) *balance.Amount {\n\tnumerator := big.NewInt(0).Mul(totalRewards.BigInt(), validatorPower)\n\treward := balance.NewAmountFromBigInt(big.NewInt(0).Div(numerator, totalPower))\n\treturn reward\n}", "func (_RewardsDistributionRecipient *RewardsDistributionRecipientSession) RewardsDistribution() (common.Address, error) {\n\treturn _RewardsDistributionRecipient.Contract.RewardsDistribution(&_RewardsDistributionRecipient.CallOpts)\n}", "func (k Keeper) DeleteReward(ctx sdk.Context, stakingCoinDenom string, farmerAcc sdk.AccAddress) {\n\tstore := ctx.KVStore(k.storeKey)\n\tstore.Delete(types.GetRewardKey(stakingCoinDenom, farmerAcc))\n\tstore.Delete(types.GetRewardByFarmerAndStakingCoinDenomIndexKey(farmerAcc, stakingCoinDenom))\n}", "func (d *Dao) UseReward(id int64, usePlat string) (rst bool, err error) {\n\tif err := d.orm.\n\t\tModel(&model.AnchorReward{}).\n\t\tWhere(\"id=?\", id).\n\t\tUpdate(map[string]interface{}{\"status\": model.RewardUsed, \"use_plat\": usePlat, \"use_time\": xtime.Time(time.Now().Unix())}).Error; err != nil {\n\t\tlog.Error(\"useReward (%v) error(%v)\", id, err)\n\t\treturn rst, err\n\t}\n\trst = true\n\treturn\n}", "func (b *EpsilonGreedy) Update(arm, reward int) {\n\t// Update the frequency\n\tb.counts[arm]++\n\tn := float64(b.counts[arm])\n\n\tvalue := b.values[arm]\n\tb.values[arm] = ((n-1)/n)*value + (1/n)*float64(reward)\n}", "func (k Keeper) ClaimUSDXMintingReward(ctx sdk.Context, owner, receiver sdk.AccAddress, multiplierName string) error {\n\tclaim, found := k.GetUSDXMintingClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, types.USDXMintingRewardDenom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", types.USDXMintingRewardDenom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tclaim, err := k.SynchronizeUSDXMintingClaim(ctx, claim)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trewardAmount := sdk.NewDecFromInt(claim.Reward.Amount).Mul(multiplier.Factor).RoundInt()\n\tif rewardAmount.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\trewardCoin := sdk.NewCoin(claim.Reward.Denom, rewardAmount)\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr = k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, sdk.NewCoins(rewardCoin), length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tk.ZeroUSDXMintingClaim(ctx, claim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claim.Reward.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, claim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func (_RewardsDistributionRecipient *RewardsDistributionRecipientTransactor) SetRewardsDistribution(opts *bind.TransactOpts, _rewardsDistribution common.Address) (*types.Transaction, error) {\n\treturn _RewardsDistributionRecipient.contract.Transact(opts, \"setRewardsDistribution\", _rewardsDistribution)\n}", "func (_RewardsDistributionRecipient *RewardsDistributionRecipientCallerSession) RewardsDistribution() (common.Address, error) {\n\treturn _RewardsDistributionRecipient.Contract.RewardsDistribution(&_RewardsDistributionRecipient.CallOpts)\n}", "func (s *BlocksService) Reward(ctx context.Context) (*BlocksReward, *http.Response, error) {\n\tvar responseStruct *BlocksReward\n\tresp, err := s.client.SendRequest(ctx, \"GET\", \"blocks/getReward\", nil, &responseStruct)\n\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn responseStruct, resp, err\n}", "func (k Keeper) ClaimDelegatorReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tclaim, found := k.GetDelegatorClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tsyncedClaim, err := k.SynchronizeDelegatorClaim(ctx, claim)\n\tif err != nil {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr = k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetDelegatorClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func MeanReward(r []*Rollout) float64 {\n\tvar sum float64\n\tfor _, x := range r {\n\t\tsum += x.Reward\n\t}\n\treturn sum / float64(len(r))\n}", "func (_Token *TokenSession) SetupRewards(multiplier *big.Int, anualRewardRates []*big.Int, lowerBounds []*big.Int, upperBounds []*big.Int) (*types.Transaction, error) {\n\treturn _Token.Contract.SetupRewards(&_Token.TransactOpts, multiplier, anualRewardRates, lowerBounds, upperBounds)\n}", "func (_Token *TokenTransactorSession) SetupRewards(multiplier *big.Int, anualRewardRates []*big.Int, lowerBounds []*big.Int, upperBounds []*big.Int) (*types.Transaction, error) {\n\treturn _Token.Contract.SetupRewards(&_Token.TransactOpts, multiplier, anualRewardRates, lowerBounds, upperBounds)\n}", "func (_Token *TokenSession) BaseReward(index *big.Int) (*big.Int, *big.Int, *big.Int, error) {\n\treturn _Token.Contract.BaseReward(&_Token.CallOpts, index)\n}", "func (_Token *TokenCallerSession) BaseReward(index *big.Int) (*big.Int, *big.Int, *big.Int, error) {\n\treturn _Token.Contract.BaseReward(&_Token.CallOpts, index)\n}", "func (q querier) RewardWeight(c context.Context, req *types.QueryRewardWeightRequest) (*types.QueryRewardWeightResponse, error) {\n\tctx := sdk.UnwrapSDKContext(c)\n\treturn &types.QueryRewardWeightResponse{RewardWeight: q.GetRewardWeight(ctx)}, nil\n}", "func (_XStaking *XStakingCaller) Rewards(opts *bind.CallOpts, arg0 common.Address) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _XStaking.contract.Call(opts, &out, \"rewards\", arg0)\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 (as AccountStorage) SetReward(ctx sdk.Context, accKey types.AccountKey, reward *Reward) sdk.Error {\n\tstore := ctx.KVStore(as.key)\n\trewardByte, err := as.cdc.MarshalJSON(*reward)\n\tif err != nil {\n\t\treturn ErrFailedToMarshalReward(err)\n\t}\n\tstore.Set(getRewardKey(accKey), rewardByte)\n\treturn nil\n}", "func (c RewardsController) CollectReward(id string) revel.Result {\n\tif !c.GetCurrentUser() {\n\t\treturn c.ForbiddenResponse()\n\t}\n\n\tif !bson.IsObjectIdHex(id) {\n\t\treturn c.ErrorResponse(nil, c.Message(\"error.invalid\", \"\"), core.ModelStatus[core.StatusInvalidID])\n\t}\n\n\tvar selector = []bson.M{\n\t\tbson.M{\"user_id\": c.CurrentUser.GetID().Hex()},\n\t\tbson.M{\"_id\": id},\n\t\tbson.M{\"multi\": false},\n\t}\n\tvar query = bson.M{\"$set\": []bson.M{\n\t\tbson.M{\"status.name\": core.StatusObtained},\n\t\tbson.M{\"status.code\": core.ValidationStatus[core.StatusObtained]},\n\t}}\n\n\t// Get pending Rewards for the user\n\tif Reward, ok := app.Mapper.GetModel(&models.Reward{}); ok {\n\t\tif err := Reward.UpdateQuery(selector, query, false); err != nil {\n\t\t\trevel.ERROR.Print(\"ERROR Find\")\n\t\t\treturn c.ErrorResponse(err, err.Error(), 400)\n\t\t}\n\t\treturn c.SuccessResponse(bson.M{\"data\": \"Reward collected successfully\"}, \"success\", core.ModelsType[core.ModelSimpleResponse], nil)\n\t}\n\n\treturn c.ServerErrorResponse()\n}", "func (b *AnnealingEpsilonGreedy) Update(arm, reward int) {\n\t// Update the frequency\n\tb.counts[arm]++\n\tn := float64(b.counts[arm])\n\n\tvalue := b.values[arm]\n\tb.values[arm] = ((n-1)/n)*value + (1/n)*float64(reward)\n}", "func GetReward(a Action, feedback Action) float64 {\n\tif a == feedback {\n\t\treturn 1\n\t}\n\treturn -1\n}", "func ViewReward(rw http.ResponseWriter, r *http.Request) {\n\t// get the token\n\treqToken := r.Header.Get(\"Authorization\")\n\t\n\t// get the claims\n\tclaims, isNotValid := GetClaims(reqToken, rw)\n\tif isNotValid {\n\t\treturn\n\t}\n\n\tdt, err := db.GetUserRewards(claims.Roll)\n\tif err != nil {\n\t\trw.WriteHeader(http.StatusInternalServerError)\n\t\trw.Write(Rsp(err.Error(), \"Server Error\"))\n\t\treturn\n\t}\n\trw.WriteHeader(http.StatusOK)\n\tres := c.RespData{\n\t\tMessage: \"All data\",\n\t\tData: dt,\n\t}\n\tjson.NewEncoder(rw).Encode(res)\n}", "func (_BondedECDSAKeep *BondedECDSAKeepFilterer) WatchETHRewardDistributed(opts *bind.WatchOpts, sink chan<- *BondedECDSAKeepETHRewardDistributed) (event.Subscription, error) {\n\n\tlogs, sub, err := _BondedECDSAKeep.contract.WatchLogs(opts, \"ETHRewardDistributed\")\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(BondedECDSAKeepETHRewardDistributed)\n\t\t\t\tif err := _BondedECDSAKeep.contract.UnpackLog(event, \"ETHRewardDistributed\", 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 (k Keeper) DistributeSavingsRate(ctx sdk.Context, debtDenom string) error {\n\tdp, found := k.GetDebtParam(ctx, debtDenom)\n\tif !found {\n\t\treturn sdkerrors.Wrap(types.ErrDebtNotSupported, debtDenom)\n\t}\n\tsavingsRateMacc := k.supplyKeeper.GetModuleAccount(ctx, types.SavingsRateMacc)\n\tsurplusToDistribute := savingsRateMacc.GetCoins().AmountOf(dp.Denom)\n\tif surplusToDistribute.IsZero() {\n\t\treturn nil\n\t}\n\n\tmodAccountCoins := k.getModuleAccountCoins(ctx, dp.Denom)\n\ttotalSupplyLessModAccounts := k.supplyKeeper.GetSupply(ctx).GetTotal().Sub(modAccountCoins)\n\tsurplusDistributed := sdk.ZeroInt()\n\tvar iterationErr error\n\tk.accountKeeper.IterateAccounts(ctx, func(acc authexported.Account) (stop bool) {\n\t\t_, ok := acc.(supplyexported.ModuleAccountI)\n\t\tif ok {\n\t\t\t// don't distribute savings rate to module accounts\n\t\t\treturn false\n\t\t}\n\t\tdebtAmount := acc.GetCoins().AmountOf(debtDenom)\n\t\tif !debtAmount.IsPositive() {\n\t\t\treturn false\n\t\t}\n\t\t// (balance * rewardToDisribute) / totalSupply\n\t\t// interest is the ratable fraction of savings rate owed to that account, rounded using bankers rounding\n\t\tinterest := (sdk.NewDecFromInt(debtAmount).Mul(sdk.NewDecFromInt(surplusToDistribute))).Quo(sdk.NewDecFromInt(totalSupplyLessModAccounts.AmountOf(debtDenom))).RoundInt()\n\t\t// sanity check, if we are going to over-distribute due to rounding, distribute only the remaining savings rate that hasn't been distributed.\n\t\tif interest.GT(surplusToDistribute.Sub(surplusDistributed)) {\n\t\t\tinterest = surplusToDistribute.Sub(surplusDistributed)\n\t\t}\n\t\t// sanity check - don't send saving rate if the rounded amount is zero\n\t\tif !interest.IsPositive() {\n\t\t\treturn false\n\t\t}\n\t\tinterestCoins := sdk.NewCoins(sdk.NewCoin(debtDenom, interest))\n\t\terr := k.supplyKeeper.SendCoinsFromModuleToAccount(ctx, types.SavingsRateMacc, acc.GetAddress(), interestCoins)\n\t\tif err != nil {\n\t\t\titerationErr = err\n\t\t\treturn true\n\t\t}\n\t\tsurplusDistributed = surplusDistributed.Add(interest)\n\t\treturn false\n\t})\n\treturn iterationErr\n}", "func (_RewardsDistributionRecipient *RewardsDistributionRecipientTransactorSession) SetRewardsDistribution(_rewardsDistribution common.Address) (*types.Transaction, error) {\n\treturn _RewardsDistributionRecipient.Contract.SetRewardsDistribution(&_RewardsDistributionRecipient.TransactOpts, _rewardsDistribution)\n}", "func (_RewardsDistributionRecipient *RewardsDistributionRecipientRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _RewardsDistributionRecipient.Contract.RewardsDistributionRecipientTransactor.contract.Transfer(opts)\n}", "func (_RandomBeacon *RandomBeaconCaller) RewardParameters(opts *bind.CallOpts) (struct {\n\tSortitionPoolRewardsBanDuration *big.Int\n\tRelayEntryTimeoutNotificationRewardMultiplier *big.Int\n\tUnauthorizedSigningNotificationRewardMultiplier *big.Int\n\tDkgMaliciousResultNotificationRewardMultiplier *big.Int\n}, error) {\n\tvar out []interface{}\n\terr := _RandomBeacon.contract.Call(opts, &out, \"rewardParameters\")\n\n\toutstruct := new(struct {\n\t\tSortitionPoolRewardsBanDuration *big.Int\n\t\tRelayEntryTimeoutNotificationRewardMultiplier *big.Int\n\t\tUnauthorizedSigningNotificationRewardMultiplier *big.Int\n\t\tDkgMaliciousResultNotificationRewardMultiplier *big.Int\n\t})\n\tif err != nil {\n\t\treturn *outstruct, err\n\t}\n\n\toutstruct.SortitionPoolRewardsBanDuration = *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\toutstruct.RelayEntryTimeoutNotificationRewardMultiplier = *abi.ConvertType(out[1], new(*big.Int)).(**big.Int)\n\toutstruct.UnauthorizedSigningNotificationRewardMultiplier = *abi.ConvertType(out[2], new(*big.Int)).(**big.Int)\n\toutstruct.DkgMaliciousResultNotificationRewardMultiplier = *abi.ConvertType(out[3], new(*big.Int)).(**big.Int)\n\n\treturn *outstruct, err\n\n}", "func (k Keeper) ClaimHardReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tk.SynchronizeHardLiquidityProviderClaim(ctx, owner)\n\n\tsyncedClaim, found := k.GetHardLiquidityProviderClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr := k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetHardLiquidityProviderClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func ValidateRewardTx(tx *types.Transaction, header *types.BlockHeader) error {\n\tif tx.Data.Type != types.TxTypeReward || !tx.Data.From.IsEmpty() || tx.Data.AccountNonce != 0 || tx.Data.GasPrice.Cmp(common.Big0) != 0 || tx.Data.GasLimit != 0 || len(tx.Data.Payload) != 0 {\n\t\treturn errInvalidReward\n\t}\n\n\t// validate to address\n\tto := tx.Data.To\n\tif to.IsEmpty() {\n\t\treturn errEmptyToAddress\n\t}\n\n\tif !to.Equal(header.Creator) {\n\t\treturn errCoinbaseMismatch\n\t}\n\n\t// validate reward\n\tamount := tx.Data.Amount\n\tif err := validateReward(amount); err != nil {\n\t\treturn err\n\t}\n\n\treward := consensus.GetReward(header.Height)\n\tif reward == nil || reward.Cmp(amount) != 0 {\n\t\treturn fmt.Errorf(\"invalid reward Amount, block height %d, want %s, got %s\", header.Height, reward, amount)\n\t}\n\n\t// validate timestamp\n\tif tx.Data.Timestamp != header.CreateTimestamp.Uint64() {\n\t\treturn errTimestampMismatch\n\t}\n\n\treturn nil\n}", "func (me *XsdGoPkgHasElem_RewardsequenceCreateHITRequestschema_Reward_TPrice_) Walk() (err error) {\n\tif fn := WalkHandlers.XsdGoPkgHasElem_RewardsequenceCreateHITRequestschema_Reward_TPrice_; 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 err = me.Reward.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\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 (_Token *TokenTransactor) SetupRewards(opts *bind.TransactOpts, multiplier *big.Int, anualRewardRates []*big.Int, lowerBounds []*big.Int, upperBounds []*big.Int) (*types.Transaction, error) {\n\treturn _Token.contract.Transact(opts, \"setupRewards\", multiplier, anualRewardRates, lowerBounds, upperBounds)\n}", "func (cra clawbackRewardAction) ProcessReward(ctx sdk.Context, reward sdk.Coins, rawAccount exported.VestingAccount) error {\n\tcva, ok := rawAccount.(*ClawbackVestingAccount)\n\tif !ok {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrNotSupported, \"expected *ClawbackVestingAccount, got %T\", rawAccount)\n\t}\n\tcva.postReward(ctx, reward, cra.ak, cra.bk, cra.sk)\n\treturn nil\n}", "func (d *ClampedRandomWalkDistribution) Advance() {\n\td.Step.Advance()\n\td.State += d.Step.Get()\n\tif d.State > d.Max {\n\t\td.State = d.Max\n\t}\n\tif d.State < d.Min {\n\t\td.State = d.Min\n\t}\n}", "func (_XStaking *XStakingTransactorSession) NotifyRewardAmount(reward *big.Int) (*types.Transaction, error) {\n\treturn _XStaking.Contract.NotifyRewardAmount(&_XStaking.TransactOpts, reward)\n}", "func (_XStaking *XStakingFilterer) WatchRewardPaid(opts *bind.WatchOpts, sink chan<- *XStakingRewardPaid, user []common.Address) (event.Subscription, error) {\n\n\tvar userRule []interface{}\n\tfor _, userItem := range user {\n\t\tuserRule = append(userRule, userItem)\n\t}\n\n\tlogs, sub, err := _XStaking.contract.WatchLogs(opts, \"RewardPaid\", userRule)\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(XStakingRewardPaid)\n\t\t\t\tif err := _XStaking.contract.UnpackLog(event, \"RewardPaid\", 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 (c *DPOS) ClaimRewardsFromAllValidators(ctx contract.Context, req *ClaimDelegatorRewardsRequest) (*ClaimDelegatorRewardsResponse, error) {\n\tif ctx.FeatureEnabled(features.DPOSVersion3_6, false) {\n\t\treturn c.claimRewardsFromAllValidators2(ctx, req)\n\t}\n\n\tdelegator := ctx.Message().Sender\n\tvalidators, err := ValidatorList(ctx)\n\tif err != nil {\n\t\treturn nil, logStaticDposError(ctx, err, req.String())\n\t}\n\n\ttotal := big.NewInt(0)\n\tchainID := ctx.Block().ChainID\n\tvar claimedFromValidators []*types.Address\n\tvar amounts []*types.BigUInt\n\tfor _, v := range validators {\n\t\tvalAddress := loom.Address{ChainID: chainID, Local: loom.LocalAddressFromPublicKey(v.PubKey)}\n\t\tdelegation, err := GetDelegation(ctx, REWARD_DELEGATION_INDEX, *valAddress.MarshalPB(), *delegator.MarshalPB())\n\t\tif err == contract.ErrNotFound {\n\t\t\t// Skip reward delegations that were not found.\n\t\t\tctx.Logger().Error(\"DPOS ClaimRewardsFromAllValidators\", \"error\", err, \"delegator\", delegator)\n\t\t\tcontinue\n\t\t} else if err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to load delegation\")\n\t\t}\n\n\t\tclaimedFromValidators = append(claimedFromValidators, valAddress.MarshalPB())\n\t\tamounts = append(amounts, delegation.Amount)\n\n\t\t// Set to UNBONDING and UpdateAmount == Amount, to fully unbond it.\n\t\tdelegation.State = UNBONDING\n\t\tdelegation.UpdateAmount = delegation.Amount\n\n\t\tif err := SetDelegation(ctx, delegation); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to update delegation\")\n\t\t}\n\n\t\terr = c.emitDelegatorUnbondsEvent(ctx, delegation)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Add to the sum\n\t\ttotal.Add(total, delegation.Amount.Value.Int)\n\t}\n\n\tamount := &types.BigUInt{Value: *loom.NewBigUInt(total)}\n\n\terr = c.emitDelegatorClaimsRewardsEvent(ctx, delegator.MarshalPB(), claimedFromValidators, amounts, amount)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &ClaimDelegatorRewardsResponse{\n\t\tAmount: amount,\n\t}, nil\n}", "func (_Lmc *LmcCaller) RewardPerBlock(opts *bind.CallOpts, arg0 *big.Int) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Lmc.contract.Call(opts, &out, \"rewardPerBlock\", arg0)\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 (d *UniformDistribution) Advance() {\n\tx := rand.Float64() // uniform\n\tx *= d.High - d.Low\n\tx += d.Low\n\td.value = x\n}", "func (_XStaking *XStakingSession) NotifyRewardAmount(reward *big.Int) (*types.Transaction, error) {\n\treturn _XStaking.Contract.NotifyRewardAmount(&_XStaking.TransactOpts, reward)\n}", "func (policy *PolicySvc) distributePolicy(policyDoc *common.Policy) error {\n\thosts, err := policy.client.ListHosts()\n\tif err != nil {\n\t\treturn err\n\t}\n\terrStr := make([]string, 0)\n\tfor _, host := range hosts {\n\t\t// TODO make schema configurable\n\t\turl := fmt.Sprintf(\"http://%s:%d/policies\", host.Ip, host.AgentPort)\n\t\tlog.Printf(\"Sending policy %s to agent at %s\", policyDoc.Name, url)\n\t\tresult := make(map[string]interface{})\n\t\terr = policy.client.Post(url, policyDoc, &result)\n\t\tlog.Printf(\"Agent at %s returned %v\", host.Ip, result)\n\t\tif err != nil {\n\t\t\terrStr = append(errStr, fmt.Sprintf(\"Error applying policy %d to host %s: %v. \", policyDoc.ID, host.Ip, err))\n\t\t}\n\t}\n\tif len(errStr) > 0 {\n\t\treturn common.NewError500(errStr)\n\t}\n\treturn nil\n}", "func (m *MemoryRewardStorage) Update(reward rewards.Reward) {\n\tfor index, r := range m.rewards {\n\t\tif r.ID == reward.ID {\n\t\t\tm.rewards[index] = reward\n\t\t}\n\t}\n}", "func (_RandomBeacon *RandomBeaconCallerSession) RewardParameters() (struct {\n\tSortitionPoolRewardsBanDuration *big.Int\n\tRelayEntryTimeoutNotificationRewardMultiplier *big.Int\n\tUnauthorizedSigningNotificationRewardMultiplier *big.Int\n\tDkgMaliciousResultNotificationRewardMultiplier *big.Int\n}, error) {\n\treturn _RandomBeacon.Contract.RewardParameters(&_RandomBeacon.CallOpts)\n}", "func playAndDistribute(ctx coretypes.Sandbox) error {\n\tctx.Event(\"playAndDistribute\")\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(\"playAndDistribute from the wrong sender\")\n\t}\n\tstate := ctx.State()\n\n\tlockedBetsArray := collections.NewArray(state, StateVarLockedBets)\n\tnumLockedBets := lockedBetsArray.MustLen()\n\tif numLockedBets == 0 {\n\t\t// nothing to play. Should not happen\n\t\treturn fmt.Errorf(\"internal error. Nothing to play\")\n\t}\n\n\t// take the entropy from the signing of the locked bets\n\t// it was saved by some 'place bet' request or otherwise it is taken from\n\t// the current context\n\tentropy, ok, _ := codec.DecodeHashValue(state.MustGet(StateVarEntropyFromLocking))\n\tif !ok {\n\t\th := ctx.GetEntropy()\n\t\tentropy = &h\n\t}\n\n\t// 'playing the wheel' means taking first 8 bytes of the entropy as uint64 number and\n\t// calculating it modulo NumColors.\n\twinningColor := byte(util.MustUint64From8Bytes(entropy[:8]) % NumColors)\n\tctx.State().Set(StateVarLastWinningColor, codec.EncodeInt64(int64(winningColor)))\n\n\tctx.Event(fmt.Sprintf(\"$$$$$$$$$$ winning color is = %d\", winningColor))\n\n\taddToWinsPerColor(ctx, winningColor)\n\n\t// take locked bets from the array\n\ttotalLockedAmount := int64(0)\n\tlockedBets := make([]*BetInfo, numLockedBets)\n\tfor i := range lockedBets {\n\t\tbi, err := DecodeBetInfo(lockedBetsArray.MustGetAt(uint16(i)))\n\t\tif err != nil {\n\t\t\t// inconsistency. Even more sad\n\t\t\tpanic(err)\n\t\t}\n\t\ttotalLockedAmount += bi.Sum\n\t\tlockedBets[i] = bi\n\t}\n\n\tctx.Event(fmt.Sprintf(\"$$$$$$$$$$ totalLockedAmount = %d\", totalLockedAmount))\n\n\t// select bets on winning Color\n\twinningBets := lockedBets[:0] // same underlying array\n\tfor _, bet := range lockedBets {\n\t\tif bet.Color == winningColor {\n\t\t\twinningBets = append(winningBets, bet)\n\t\t}\n\t}\n\n\tctx.Event(fmt.Sprintf(\"$$$$$$$$$$ winningBets: %d\", len(winningBets)))\n\n\t// locked bets neither entropy are not needed anymore\n\tlockedBetsArray.MustErase()\n\tstate.Del(StateVarEntropyFromLocking)\n\n\tif len(winningBets) == 0 {\n\n\t\tctx.Event(fmt.Sprintf(\"$$$$$$$$$$ nobody wins: amount of %d stays in the smart contract\", totalLockedAmount))\n\n\t\t// nobody played on winning Color -> all sums stay in the smart contract\n\t\t// move tokens to itself.\n\t\t// It is not necessary because all tokens are in the own account anyway.\n\t\t// However, it is healthy to compress number of outputs in the address\n\n\t\t//agent := coretypes.NewAgentIDFromContractID(ctx.ContractID())\n\t\t//if !ctx.MoveTokens(agent, balance.ColorIOTA, totalLockedAmount) {\n\t\t//\t// inconsistency. A disaster\n\t\t//\tctx.Event(fmt.Sprintf(\"$$$$$$$$$$ something went wrong 1\"))\n\t\t//\tctx.Log().Panicf(\"MoveTokens failed\")\n\t\t//}\n\t}\n\n\t// distribute total staked amount to players\n\tif !distributeLockedAmount(ctx, winningBets, totalLockedAmount) {\n\t\tctx.Event(fmt.Sprintf(\"$$$$$$$$$$ something went wrong 2\"))\n\t\tctx.Log().Panicf(\"distributeLockedAmount failed\")\n\t}\n\n\tfor _, betInfo := range winningBets {\n\t\terr := withPlayerStats(ctx, &betInfo.Player, func(ps *PlayerStats) {\n\t\t\tps.Wins += 1\n\t\t})\n\t\tif err != nil {\n\t\t\tctx.Log().Panicf(\"%v\", err)\n\t\t}\n\t}\n\treturn nil\n}", "func (_BondedECDSAKeep *BondedECDSAKeepFilterer) FilterETHRewardDistributed(opts *bind.FilterOpts) (*BondedECDSAKeepETHRewardDistributedIterator, error) {\n\n\tlogs, sub, err := _BondedECDSAKeep.contract.FilterLogs(opts, \"ETHRewardDistributed\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &BondedECDSAKeepETHRewardDistributedIterator{contract: _BondedECDSAKeep.contract, event: \"ETHRewardDistributed\", logs: logs, sub: sub}, nil\n}", "func (k Keeper) DistributeDrops(ctx sdk.Context, height int64, DistributionName string, runner sdk.AccAddress, distributionType types.DistributionType) (types.DistributionRecords, error) {\n\t// TODO replace 10 with a variable declared in genesis or a constant in keys.go.\n\tpendingRecords := k.GetRecordsForNamePendingLimited(ctx, DistributionName, 10, runner, distributionType)\n\tfor _, record := range pendingRecords {\n\t\terr := k.GetSupplyKeeper().SendCoinsFromModuleToAccount(ctx, types.ModuleName, record.RecipientAddress, record.Coins)\n\t\tif err != nil {\n\t\t\terr := errors.Wrapf(err, \"Distribution failed for address : %s\", record.RecipientAddress.String())\n\t\t\tctx.Logger().Error(err.Error())\n\t\t\terr = k.MoveRecordToFailed(ctx, record)\n\t\t\tif err != nil {\n\t\t\t\treturn pendingRecords, errors.Wrapf(err, \"Unable to set Distribution Records to Failed : %s\", record.String())\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\trecord.DistributionStatus = types.Completed\n\t\trecord.DistributionCompletedHeight = height\n\t\terr = k.SetDistributionRecord(ctx, record)\n\t\tif err != nil {\n\t\t\terr := errors.Wrapf(types.ErrFailedOutputs, \"error setting distibution record : %s\", record.String())\n\t\t\tctx.Logger().Error(err.Error())\n\t\t\t// If the SetDistributionRecord returns error , that would mean the required amount was transferred to the user , but the record was not set to completed .\n\t\t\t// In this case we try to take the funds back from the user , and attempt the withdrawal later .\n\t\t\terr = k.GetSupplyKeeper().SendCoinsFromAccountToModule(ctx, record.RecipientAddress, types.ModuleName, record.Coins)\n\t\t\tif err != nil {\n\t\t\t\treturn pendingRecords, errors.Wrapf(err, \"Unable to set Distribution Records to completed : %s\", record.String())\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\t// Use record details to delete associated claim\n\t\t// The claim should always be locked at this point in time .\n\t\tif record.DoesClaimExist() {\n\t\t\tk.DeleteClaim(ctx, record.RecipientAddress.String(), record.DistributionType)\n\t\t}\n\t\tctx.Logger().Info(fmt.Sprintf(\"Distributed to : %s | At height : %d | Amount :%s \\n\", record.RecipientAddress.String(), height, record.Coins.String()))\n\t}\n\treturn pendingRecords, nil\n}", "func bindRewardsDistributionRecipient(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) {\n\tparsed, err := abi.JSON(strings.NewReader(RewardsDistributionRecipientABI))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil\n}", "func NewRewardTx(coinbase common.Address, reward *big.Int, timestamp uint64) (*types.Transaction, error) {\n\tif err := validateReward(reward); err != nil {\n\t\treturn nil, err\n\t}\n\n\ttxData := types.TransactionData{\n\t\tType: types.TxTypeReward,\n\t\tFrom: common.EmptyAddress,\n\t\tTo: coinbase,\n\t\tAmount: new(big.Int).Set(reward),\n\t\tGasPrice: common.Big0,\n\t\tTimestamp: timestamp,\n\t\tPayload: emptyPayload,\n\t}\n\n\ttx := types.Transaction{\n\t\tHash: crypto.MustHash(txData),\n\t\tData: txData,\n\t\tSignature: emptySig,\n\t}\n\n\treturn &tx, nil\n}", "func (_Smartchef *SmartchefCaller) RewardPerBlock(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Smartchef.contract.Call(opts, out, \"rewardPerBlock\")\n\treturn *ret0, err\n}", "func (_XStaking *XStakingFilterer) FilterRewardPaid(opts *bind.FilterOpts, user []common.Address) (*XStakingRewardPaidIterator, error) {\n\n\tvar userRule []interface{}\n\tfor _, userItem := range user {\n\t\tuserRule = append(userRule, userItem)\n\t}\n\n\tlogs, sub, err := _XStaking.contract.FilterLogs(opts, \"RewardPaid\", userRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &XStakingRewardPaidIterator{contract: _XStaking.contract, event: \"RewardPaid\", logs: logs, sub: sub}, nil\n}", "func (rig *testRig) redeem_taker(checkStatus bool) error {\n\tmatchInfo := rig.matchInfo\n\tmatchInfo.db.takerRedeem = rig.redeem(matchInfo.taker, matchInfo.takerOID)\n\ttracker := rig.getTracker()\n\t// Check the match status\n\tif checkStatus {\n\t\tif tracker != nil {\n\t\t\treturn fmt.Errorf(\"expected match to be removed, found it, in status %v\", tracker.Status)\n\t\t}\n\t\terr := rig.checkResponse(matchInfo.taker, \"redeem\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (d *MonotonicRandomWalkDistribution) Advance() {\n\td.Step.Advance()\n\td.State += math.Abs(d.Step.Get())\n}" ]
[ "0.6758821", "0.64290905", "0.6397762", "0.63100404", "0.60241735", "0.59990525", "0.59793544", "0.5928813", "0.585137", "0.57938814", "0.5633375", "0.5522693", "0.54059565", "0.537793", "0.5369064", "0.5322376", "0.5290096", "0.52899516", "0.5289859", "0.52838886", "0.5282563", "0.5234018", "0.5166412", "0.5163699", "0.51494277", "0.5144747", "0.50842685", "0.50770324", "0.5039137", "0.50101125", "0.49886718", "0.4988388", "0.49669877", "0.49592102", "0.4948811", "0.494178", "0.49381617", "0.493457", "0.49325964", "0.49171472", "0.48805666", "0.48743045", "0.48628837", "0.48465478", "0.48309922", "0.4829738", "0.4823581", "0.48001027", "0.4750146", "0.47495374", "0.47492865", "0.47134227", "0.46927372", "0.46913937", "0.46752006", "0.466761", "0.46651492", "0.46616465", "0.46527112", "0.46466953", "0.4635468", "0.4629587", "0.46258375", "0.462531", "0.46225235", "0.46146473", "0.46126884", "0.46081883", "0.46007314", "0.45919257", "0.45816714", "0.45802513", "0.45751968", "0.45697722", "0.4567867", "0.45586684", "0.45576894", "0.4543228", "0.45253262", "0.45234728", "0.4519767", "0.45107132", "0.4508761", "0.44949284", "0.44897395", "0.44887808", "0.4485532", "0.4482852", "0.44771755", "0.44762224", "0.44708928", "0.44706833", "0.4467554", "0.44598237", "0.44569808", "0.44539884", "0.44505754", "0.44497564", "0.44492695", "0.44488573" ]
0.7879191
0
scaleCoins scales the given coins, rounding down.
scaleCoins масштабирует заданные монеты, округляя вниз.
func scaleCoins(coins sdk.Coins, scale sdk.Dec) sdk.Coins { scaledCoins := sdk.NewCoins() for _, coin := range coins { amt := coin.Amount.ToDec().Mul(scale).TruncateInt() // round down scaledCoins = scaledCoins.Add(sdk.NewCoin(coin.Denom, amt)) } return scaledCoins }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (blk *Block) Scale(sx, sy float64) {\n\tops := contentstream.NewContentCreator().\n\t\tScale(sx, sy).\n\t\tOperations()\n\n\t*blk.contents = append(*ops, *blk.contents...)\n\tblk.contents.WrapIfNeeded()\n\n\tblk.width *= sx\n\tblk.height *= sy\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 (c *LinehaulCostComputation) Scale(factor float64) {\n\tc.BaseLinehaul = c.BaseLinehaul.MultiplyFloat64(factor)\n\tc.OriginLinehaulFactor = c.OriginLinehaulFactor.MultiplyFloat64(factor)\n\tc.DestinationLinehaulFactor = c.DestinationLinehaulFactor.MultiplyFloat64(factor)\n\tc.ShorthaulCharge = c.ShorthaulCharge.MultiplyFloat64(factor)\n\tc.LinehaulChargeTotal = c.LinehaulChargeTotal.MultiplyFloat64(factor)\n}", "func scale(dst *block, src *[4]block) {\n\tfor i := 0; i < 4; i++ {\n\t\tdstOff := (i&2)<<4 | (i&1)<<2\n\t\tfor y := 0; y < 4; y++ {\n\t\t\tfor x := 0; x < 4; x++ {\n\t\t\t\tj := 16*y + 2*x\n\t\t\t\tsum := src[i][j] + src[i][j+1] + src[i][j+8] + src[i][j+9]\n\t\t\t\tdst[8*y+x+dstOff] = (sum + 2) >> 2\n\t\t\t}\n\t\t}\n\t}\n}", "func scale(val float64, min float64, max float64, outMin float64, outMax float64) float64 {\r\n\tdenom := 1.0\r\n\ty := 0.0\r\n\tif outMin - min != 0 {\r\n\t\tdenom = outMin - min\r\n\t\ty = (outMax - max) / denom * val - min + outMin\r\n\t} else {\r\n\t\ty = outMax / max * val - min + outMin\r\n\t}\r\n\treturn y\r\n}", "func (canvas *Canvas) Scale(x, y float32) {\n\twriteCommand(canvas.contents, \"cm\", x, 0, 0, y, 0, 0)\n}", "func ScaleRecipe(amounts []float64, portions int) []float64 {\n\tscale := float64(portions) / 2.0\n\tscaledAmounts := make([]float64, len(amounts))\n\tfor ingredient, amount := range amounts {\n\t\tscaledAmounts[ingredient] = amount * scale\n\t}\n\treturn scaledAmounts\n}", "func Scale(zoom float64) float64 {\n\treturn 256 * math.Pow(2, zoom)\n}", "func (v Vector) Scale(c float64) Vector {\n\tfor i, x := range v {\n\t\tv[i] = x * c\n\t}\n\treturn v\n}", "func (s SamplesC64) Scale(r float32) {\n\tsimd.ScaleComplex(r, s)\n}", "func scale(bytes int64) (scaled int64, scale string) {\n\tif bytes < 0 {\n\t\tscaled, scale = uscale(uint64(bytes * -1))\n\t\tscaled *= -1\n\t} else {\n\t\tscaled, scale = uscale(uint64(bytes))\n\t}\n\treturn\n}", "func (keeper Keeper) SetCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) sdk.Error {\n\treturn setCoins(ctx, keeper.am, addr, amt)\n}", "func (c *Circle) Scale(f float64) {\n\tc.radius *= f\n}", "func (c Charset) Scale(factor int) {\n\tif factor <= 1 {\n\t\t// A factor of zero results in zero-sized glyphs and\n\t\t// is therefore not valid. A factor of 1 does not change\n\t\t// the glyphs, so we can ignore it.\n\t\treturn\n\t}\n\n\t// Multiply each glyph field by the given factor\n\t// to scale them up to the new size.\n\tfor i := range c {\n\t\tc[i].X *= factor\n\t\tc[i].Y *= factor\n\t\tc[i].Width *= factor\n\t\tc[i].Height *= factor\n\t\tc[i].Advance *= factor\n\t}\n}", "func (m *mover) EarnCoins(tx *TX, limits, coins map[string]int) error {\n\tbank, err := tx.GetCoins()\n\tif err != nil {\n\t\treturn err\n\t}\n\tpurse, err := tx.GetPlayerCoins(m.userID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor color, limit := range limits {\n\t\tif bank[color] < limit {\n\t\t\treturn ErrInsufficientCoins\n\t\t}\n\t}\n\n\tnewbank := map[string]int{}\n\tnewpurse := map[string]int{}\n\n\tfor color, count := range coins {\n\t\tnewbank[color] = bank[color] - count\n\t\tnewpurse[color] = purse[color] + count\n\t}\n\n\tif err := tx.UpdateCoins(newbank); err != nil {\n\t\treturn err\n\t}\n\tif err := tx.UpdatePlayerCoins(m.userID, newpurse); err != nil {\n\t\treturn err\n\t}\n\n\t// TODO: If player has more than 10 coins now, make then give some back.\n\n\treturn nil\n}", "func (v *Vector) ScaleTo(s float64) {\n\tv.X = s * v.X\n\tv.Y = s * v.Y\n\tv.Z = s * v.Z\n}", "func Scale(A float64, x *Matrix) (*Matrix, error) {\n\tout, _ := New(x.RowCount, x.ColCount, nil)\n\n\tfor rowID := 0; rowID < x.RowCount; rowID++ {\n\t\tfor colID := 0; colID < x.ColCount; colID++ {\n\t\t\tout.Matrix[rowID][colID] = A * x.Matrix[rowID][colID]\n\t\t}\n\t}\n\n\treturn out, nil\n}", "func intScale(val int, val_range int, out_range int) int {\n\tnum := val*(out_range-1)*2 + (val_range - 1)\n\tdem := (val_range - 1) * 2\n\treturn num / dem\n}", "func (dw *DrawingWand) Scale(x, y float64) {\n\tC.MagickDrawScale(dw.dw, C.double(x), C.double(y))\n}", "func (t *Transform) Scale(sx, sy float64) {\n\tout := fmt.Sprintf(\"scale(%g,%g)\", sx, sy)\n\n\tt.transforms = append(t.transforms, out)\n}", "func (c2d *C2DMatrix) Scale(xScale, yScale float64) {\n\tvar mat Matrix\n\n\tmat.m11 = xScale\n\tmat.m12 = 0\n\tmat.m13 = 0\n\n\tmat.m21 = 0\n\tmat.m22 = yScale\n\tmat.m23 = 0\n\n\tmat.m31 = 0\n\tmat.m32 = 0\n\tmat.m33 = 1\n\n\t//and multiply\n\tc2d.MatrixMultiply(mat)\n}", "func (q1 Quat) Scale(c float32) Quat {\n\treturn Quat{q1.W * c, Vec3{q1.V[0] * c, q1.V[1] * c, q1.V[2] * c}}\n}", "func (wv *Spectrum) Scale(s float32) {\n\twv.C[0] *= s\n\twv.C[1] *= s\n\twv.C[2] *= s\n\twv.C[3] *= s\n}", "func Change(money int, coins []int) int {\n\tminNumCoins := make([]int, money+1)\n\n\t// range over all relevant values of k\n\tfor k := 1; k <= money; k++ {\n\t\t// take minimum of all relevant values at each step\n\t\tvar currentMin int\n\t\tfor i := range coins {\n\t\t\t// make sure that current coin isn't too big\n\t\t\tif k-coins[i] >= 0 {\n\t\t\t\tif minNumCoins[k-coins[i]] == 0 && k-coins[i] != 0 {\n\t\t\t\t\tpanic(\"Bad\")\n\t\t\t\t}\n\t\t\t\t//we're OK\n\t\t\t\tif i == 0 || minNumCoins[k-coins[i]] < currentMin {\n\t\t\t\t\tcurrentMin = minNumCoins[k-coins[i]]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// update my minNumCoins[k] value\n\t\tminNumCoins[k] = currentMin + 1\n\t}\n\n\treturn minNumCoins[money]\n}", "func ScaleResources(resourceName corev1.ResourceName, quantity *resource.Quantity, factor float32) {\n\tswitch resourceName {\n\tcase corev1.ResourceCPU:\n\t\t// use millis\n\t\tquantity.SetScaled(int64(float32(quantity.MilliValue())*factor), resource.Milli)\n\tcase corev1.ResourceMemory:\n\t\t// use mega\n\t\tquantity.SetScaled(int64(float32(quantity.ScaledValue(resource.Mega))*factor), resource.Mega)\n\tdefault:\n\t\tquantity.Set(int64(float32(quantity.Value()) * factor))\n\t}\n}", "func (m *Matrix3) Scale(s float64) {\n\tfor i, x := range m {\n\t\tm[i] = x * s\n\t}\n}", "func (ex *ExampleMNIST3D) scaleSprites() {\n\n\tfor i := 0; i < len(ex.sprites); i++ {\n\t\tex.sprites[i].SetScale(ex.spriteScale, ex.spriteScale, ex.spriteScale)\n\t}\n}", "func coinChange(coins []int, amount int) int {\n\tmin := func(x, y int) int {\n\t\tif x < y {\n\t\t\treturn x\n\t\t}\n\t\treturn y\n\t}\n\n\tsums := make([]int, amount+1)\n\tfor i := 1; i <= amount; i++ {\n\t\tsums[i] = math.MaxInt32\n\t\tfor j := 0; j < len(coins); j++ {\n\t\t\tif coins[j] <= i {\n\t\t\t\tsums[i] = min(sums[i], sums[i-coins[j]]+1)\n\t\t\t}\n\t\t}\n\t}\n\n\tif sums[amount] == math.MaxInt32 {\n\t\treturn -1\n\t}\n\n\treturn sums[amount]\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 (p *Proc) Scale(x, y float64) {\n\tp.stk.scale(x, y)\n}", "func scale(a, maxA, maxB int) float64 {\n\treturn (float64(a) / float64(maxA)) * float64(maxB) + 1\n}", "func Scale(value float64) *SimpleElement { return newSEFloat(\"scale\", value) }", "func (c *canvasRenderer) Scale(amount sprec.Vec2) {\n\tc.currentLayer.Transform = sprec.Mat4Prod(\n\t\tc.currentLayer.Transform,\n\t\tsprec.ScaleMat4(amount.X, amount.Y, 1.0),\n\t)\n}", "func coins(a int) int {\n\tif a == 0 {\n\t\treturn 0\n\t}\n\treturn doCoins(a, 25)\n}", "func (s *Simulator) FormatCoins(coins sdk.Coins) string {\n\tout := make([]string, 0, len(coins))\n\tfor _, coin := range coins {\n\t\tout = append(out, s.FormatIntDecimals(coin.Amount, s.stakingAmountDecimalsRatio)+coin.Denom)\n\t}\n\n\treturn strings.Join(out, \",\")\n}", "func (v Vec3) Scale(s float64) Vec3 {\n\treturn Vec3{v[0] * s, v[1] * s, v[2] * s}\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 ratScale(x *big.Rat, exp int) {\n\tif exp < 0 {\n\t\tx.Inv(x)\n\t\tratScale(x, -exp)\n\t\tx.Inv(x)\n\t\treturn\n\t}\n\tfor exp >= 9 {\n\t\tx.Quo(x, bigRatBillion)\n\t\texp -= 9\n\t}\n\tfor exp >= 1 {\n\t\tx.Quo(x, bigRatTen)\n\t\texp--\n\t}\n}", "func generateScale(adx *header, samplesPerBlock byte, scaledSampleErrorNibbles []int32) []uint16 {\n\n\tscale := make([]uint16, adx.channelCount)\n\n\tfor i := byte(0); i < adx.channelCount; i++ {\n\n\t\t// Get max reach\n\t\tminAbsErr := scaledSampleErrorNibbles[samplesPerBlock*i+0]\n\t\tmaxAbsErr := scaledSampleErrorNibbles[samplesPerBlock*i+0]\n\t\tfor j := byte(0); j < samplesPerBlock; j++ {\n\n\t\t\tv := scaledSampleErrorNibbles[samplesPerBlock*i+j]\n\n\t\t\tif v > maxAbsErr {\n\t\t\t\tmaxAbsErr = v\n\t\t\t}\n\t\t\tif v < minAbsErr {\n\t\t\t\tminAbsErr = v\n\t\t\t}\n\t\t}\n\n\t\t// Calculate scale\n\t\tif maxAbsErr > 0 && minAbsErr < 0 {\n\t\t\tif maxAbsErr > -minAbsErr {\n\t\t\t\tscale[i] = uint16(maxAbsErr / 7)\n\t\t\t} else {\n\t\t\t\tscale[i] = uint16(minAbsErr / -8)\n\t\t\t}\n\t\t} else if minAbsErr > 0 {\n\t\t\tscale[i] = uint16(maxAbsErr / 7)\n\t\t} else if maxAbsErr < 0 {\n\t\t\tscale[i] = uint16(minAbsErr / -8)\n\t\t}\n\t}\n\n\treturn scale\n}", "func scale(v []int, x int) []int {\n\ty := make([]int, len(v))\n\tfor i := range v {\n\t\ty[i] = v[i] * x\n\t}\n\treturn y\n}", "func (ki *KernelInfo) Scale(scale float64, normalizeType KernelNormalizeType) {\n\tC.ScaleKernelInfo(ki.info, C.double(scale), C.GeometryFlags(normalizeType))\n\truntime.KeepAlive(ki)\n}", "func (dev *pwm_context) Scale(value int) error {\n\tif dev.period == -1 {\n\t\tif err := dev.ReadPeriod(); err != nil {\n\t\t\treturn fmt.Errorf(\"pwm: error running Scale: %s\", err)\n\t\t}\n\t}\n\n\tduty := (float64(value) - dev.min) / dev.span\n\tfmt.Printf(\"pwm: Scaling pin[%d] from value: %d to duty: %f\\n\", dev.pin, value, duty)\n\treturn dev.WriteDuty(int(float64(dev.period) * duty))\n}", "func (t *Tree) Scale(s float32) {\n\tif t.Leaf != nil {\n\t\tfor i, x := range t.Leaf.OutputDelta {\n\t\t\tt.Leaf.OutputDelta[i] = x * s\n\t\t}\n\t} else {\n\t\tt.Branch.FalseBranch.Scale(s)\n\t\tt.Branch.TrueBranch.Scale(s)\n\t}\n}", "func (c *nodePools) Scale(id string, req *types.NodePoolScaleRequest) (*types.NodePool, error) {\n\tpath := fmt.Sprintf(\"/v3/organizations/%s/clusters/%s/node-pools/%s\", c.organizationID, c.clusterID, id)\n\tvar out types.NodePool\n\treturn &out, c.client.Patch(path, req, &out)\n}", "func coinChange(coins []int, amount int) int {\n\tdp := make([]int, amount+1)\n\tfor i := 0; i < len(dp); i++ {\n\t\tdp[i] = amount + 1\n\t}\n\tdp[0] = 0\n\tfor i := 1; i <= amount; i++ {\n\t\tfor _, coin := range coins {\n\t\t\tif coin <= i {\n\t\t\t\tdp[i] = utils.Min(dp[i-coin]+1, dp[i])\n\t\t\t}\n\t\t}\n\t}\n\tif dp[amount] > amount {\n\t\treturn -1\n\t}\n\treturn dp[amount]\n}", "func Scale(s Frac, m M) M {\n\tm = CopyMatrix(m)\n\n\tfor r := 1; r <= m.Rows(); r++ {\n\t\tm.MultiplyRow(r, s)\n\t}\n\n\treturn m\n}", "func (v *V_elem) Scale(ofs, scale *[3]float32) *[3]int {\n\treturn &[3]int{\n\t\tint((v.x[0] + ofs[0]) * scale[0]),\n\t\tint((v.x[1] + ofs[1]) * scale[1]),\n\t\tint((v.x[2] + ofs[2]) * scale[2]),\n\t}\n}", "func (mw *MagickWand) Scale(cols, rows uint) error {\n\treturn mw.ScaleImage(cols, rows)\n}", "func Scale(w, h int) int {\n\ta := w / WIDTH\n\tb := h / HEIGHT\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func Quat2Scale(out, a []float64, b float64) []float64 {\n\tout[0] = a[0] * b\n\tout[1] = a[1] * b\n\tout[2] = a[2] * b\n\tout[3] = a[3] * b\n\tout[4] = a[4] * b\n\tout[5] = a[5] * b\n\tout[6] = a[6] * b\n\tout[7] = a[7] * b\n\treturn out\n}", "func coinChange(coins []int, amount int) int {\n\t// dp[i]: The minimum changes needed for money: i.\n\tdp := make([]int, amount+1)\n\tdp[0] = 0\n\n\t// Initialize dynamic programming boundary.\n\tfor i := 1; i <= amount; i++ {\n\t\tdp[i] = amount + 1\n\t}\n\n\tfor m := 1; m <= amount; m++ {\n\t\t// Reset minChanges.\n\t\tminChanges := amount + 1\n\n\t\t// For money: m\n\t\t// dp[m] = Minimum changes needed for money: m - coins[j] + 1.\n\t\t// i.e. dp[m] = min(m - coins[j]) + 1, where j = 0 -> len(coins)-1.\n\t\tfor _, c := range coins {\n\t\t\tchange := m - c\n\n\t\t\tif change < 0 {\n\t\t\t\t// Cannot make change, continue.\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Update minChanges.\n\t\t\tif dp[change] < minChanges {\n\t\t\t\tminChanges = dp[change]\n\t\t\t}\n\t\t}\n\n\t\tdp[m] = minChanges + 1\n\t}\n\n\t// Nothing can be changed, return -1.\n\tif dp[amount] > amount {\n\t\treturn -1\n\t}\n\n\treturn dp[amount]\n}", "func (s *Surface) Scale(x, y float64) {\n\ts.Ctx.Call(\"scale\", x, y)\n}", "func (blk *Block) ScaleToWidth(w float64) {\n\tratio := w / blk.width\n\tblk.Scale(ratio, ratio)\n}", "func linearScale(value, min, max float64) float64 {\n\treturn (value - min) * (1 / (max - min))\n}", "func (c *RGB) Scale(f float32) {\n\tfor k := range c {\n\t\tc[k] *= f\n\t}\n}", "func (ct *Ciphertext) SetScalingFactor(scale float64) {\n\tct.Scale = scale\n}", "func (p *point) scaleBy(factor int) {\n\tp.x *= factor\n\tp.y *= factor\n}", "func (blk *Block) ScaleToHeight(h float64) {\n\tratio := h / blk.height\n\tblk.Scale(ratio, ratio)\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 (k Keeper) BurnCoins(ctx sdk.Context, moduleName types.AccountID, amt Coins) error {\n\tacc := k.GetModuleAccount(ctx, moduleName.String())\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\terr := k.SendCoinsFromModuleToModule(ctx, moduleName.String(), types.BlackHole, amt)\n\tif err != nil {\n\t\treturn sdkerrors.Wrapf(err, \"burn coins error by sub coin power\")\n\t}\n\n\tk.Logger(ctx).Info(fmt.Sprintf(\"burned %s from %s module account\", amt.String(), moduleName))\n\n\treturn nil\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 (x *Big) Scale() int { return -x.exp }", "func flipCoins(n int) int {\n\tvar i int\n\tfor i = 0; n > 1; i++ {\n\t\tn = round(n)\n\t}\n\treturn i\n}", "func drawCoins() int {\n\treturn rand.Intn(maxCoins+1-minCoins) + minCoins\n}", "func (s Size) ScaleUp(x, y int) Size {\n\ts.W *= x\n\ts.H *= y\n\treturn s\n}", "func (o ContainerOutput) Scale() pulumi.IntOutput {\n\treturn o.ApplyT(func(v *Container) pulumi.IntOutput { return v.Scale }).(pulumi.IntOutput)\n}", "func Scale(s float64) Matrix {\n\treturn Matrix{s, 0, 0, s, 0, 0}\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 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) MintCoins(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.Minter) {\n\t\tpanic(sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, \"module account %s does not have permissions to mint tokens\", moduleName))\n\t}\n\n\t_, err := k.bk.AddCoins(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.Inflate(amt)\n\n\tk.SetSupply(ctx, supply)\n\n\tlogger := k.Logger(ctx)\n\tlogger.Info(fmt.Sprintf(\"minted %s from %s module account\", amt.String(), moduleName))\n\n\treturn nil\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 Scale(out *NArray, in *NArray, c float32) *NArray {\n\n\tif out == nil {\n\t\tout = New(in.Shape...)\n\t} else {\n\t\tif !EqualShape(out, in) {\n\t\t\tpanic(\"narrays must have equal shape.\")\n\t\t}\n\t}\n\tcmulSlice(out.Data, in.Data, c)\n\treturn out\n}", "func ScaleSprite(src *ebiten.Image, x, y float64) (*ebiten.Image, error) {\n\tspriteW, spriteH := src.Size()\n\tsSprite, sSpriteErr := ebiten.NewImage(\n\t\tint(float64(spriteW)*x),\n\t\tint(float64(spriteH)*y),\n\t\tebiten.FilterDefault)\n\tif sSpriteErr != nil {\n\t\treturn nil, sSpriteErr\n\t}\n\n\tops := &ebiten.DrawImageOptions{}\n\tops.GeoM.Scale(x, y)\n\tif drawErr := sSprite.DrawImage(src, ops); drawErr != nil {\n\t\treturn nil, drawErr\n\t}\n\n\treturn sSprite, nil\n}", "func change(amount int, coins []int) int {\n\tmemo := make([][]int, len(coins)+1)\n\tfor x := range memo {\n\t\tmemo[x] = make([]int, amount+1)\n\t}\n\n\tmemo[0][0] = 1\n\n\tfor x, coin := range coins {\n\t\tmemo[x+1][0] = 1\n\t\tfor y := 1; y <= amount; y++ {\n\t\t\tmemo[x+1][y] = memo[x][y] // exclude current coin - take the amount of previous coin\n\t\t\tif coin <= y {\n\t\t\t\tmemo[x+1][y] += memo[x+1][y-coin] // try to include current coin\n\t\t\t}\n\t\t}\n\t}\n\n\treturn memo[len(coins)][amount]\n}", "func (k Keeper) SwapDecCoins(ctx sdk.Context, offerCoin sdk.DecCoin, askDenom string) (sdk.DecCoin, sdk.Error) {\n\tofferRate, err := k.ok.GetLunaSwapRate(ctx, offerCoin.Denom)\n\tif err != nil {\n\t\treturn sdk.DecCoin{}, ErrNoEffectivePrice(DefaultCodespace, offerCoin.Denom)\n\t}\n\n\taskRate, err := k.ok.GetLunaSwapRate(ctx, askDenom)\n\tif err != nil {\n\t\treturn sdk.DecCoin{}, ErrNoEffectivePrice(DefaultCodespace, askDenom)\n\t}\n\n\tretAmount := offerCoin.Amount.Mul(askRate).Quo(offerRate)\n\tif retAmount.LTE(sdk.ZeroDec()) {\n\t\treturn sdk.DecCoin{}, ErrInsufficientSwapCoins(DefaultCodespace, offerCoin.Amount.TruncateInt())\n\t}\n\n\treturn sdk.NewDecCoinFromDec(askDenom, retAmount), nil\n}", "func Scale(appName string, webCount int, workerCount int) error {\n\targs := []string{\"dokku\", \"ps:scale\", appName}\n\n\tif webCount > 0 {\n\t\twebPart := fmt.Sprintf(\"web=%v\", webCount)\n\t\targs = append(args, webPart)\n\t}\n\n\tif workerCount > 0 {\n\t\tworkerPart := fmt.Sprintf(\"worker=%v\", workerCount)\n\t\targs = append(args, workerPart)\n\t}\n\n\tlog.GeneralLogger.Println(args)\n\tcmd := common.NewShellCmd(strings.Join(args, \" \"))\n\tcmd.ShowOutput = false\n\tout, err := cmd.Output()\n\n\tif err != nil {\n\t\tlog.ErrorLogger.Println(\"Dokku ps:scale error:\", err.Error())\n\t\tlog.ErrorLogger.Println(\"Dokku ps:scale output:\", string(out))\n\t\treturn err\n\t}\n\tlog.GeneralLogger.Println(\"Dokku ps:scale output:\", string(out))\n\treturn nil\n}", "func CoinChange(coins []int, amount int) int {\n\tdp := make([]int, amount+1)\n\tdp[0] = 0\n\tfor i := 1; i < len(dp); i++ {\n\t\tdp[i] = -1\n\t}\n\n\tfor i := 0; i <= amount; i++ {\n\t\tminChange := math.MaxInt16\n\t\tfor _, coin := range coins {\n\t\t\tif i-coin < 0 || dp[i-coin] == -1 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tminChange = min([]int{dp[i-coin], minChange})\n\t\t}\n\n\t\tif minChange != math.MaxInt16 {\n\t\t\tdp[i] = 1 + minChange\n\t\t}\n\t}\n\treturn dp[amount]\n}", "func (m *Manager) Scale(shardIDs []int, shardCount int) (err error) {\n\tsg, err := NewShardGroup(m, shardIDs, shardCount)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = sg.Start()\n\treturn\n}", "func (dc *DeploymentController) scale(ctx context.Context, deployment *apps.Deployment, newRS *apps.ReplicaSet, oldRSs []*apps.ReplicaSet) error {\n\t// If there is only one active replica set then we should scale that up to the full count of the\n\t// deployment. If there is no active replica set, then we should scale up the newest replica set.\n\tif activeOrLatest := deploymentutil.FindActiveOrLatest(newRS, oldRSs); activeOrLatest != nil {\n\t\tif *(activeOrLatest.Spec.Replicas) == *(deployment.Spec.Replicas) {\n\t\t\treturn nil\n\t\t}\n\t\t_, _, err := dc.scaleReplicaSetAndRecordEvent(ctx, activeOrLatest, *(deployment.Spec.Replicas), deployment)\n\t\treturn err\n\t}\n\n\t// If the new replica set is saturated, old replica sets should be fully scaled down.\n\t// This case handles replica set adoption during a saturated new replica set.\n\tif deploymentutil.IsSaturated(deployment, newRS) {\n\t\tfor _, old := range controller.FilterActiveReplicaSets(oldRSs) {\n\t\t\tif _, _, err := dc.scaleReplicaSetAndRecordEvent(ctx, old, 0, deployment); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\n\t// There are old replica sets with pods and the new replica set is not saturated.\n\t// We need to proportionally scale all replica sets (new and old) in case of a\n\t// rolling deployment.\n\tif deploymentutil.IsRollingUpdate(deployment) {\n\t\tallRSs := controller.FilterActiveReplicaSets(append(oldRSs, newRS))\n\t\tallRSsReplicas := deploymentutil.GetReplicaCountForReplicaSets(allRSs)\n\n\t\tallowedSize := int32(0)\n\t\tif *(deployment.Spec.Replicas) > 0 {\n\t\t\tallowedSize = *(deployment.Spec.Replicas) + deploymentutil.MaxSurge(*deployment)\n\t\t}\n\n\t\t// Number of additional replicas that can be either added or removed from the total\n\t\t// replicas count. These replicas should be distributed proportionally to the active\n\t\t// replica sets.\n\t\tdeploymentReplicasToAdd := allowedSize - allRSsReplicas\n\n\t\t// The additional replicas should be distributed proportionally amongst the active\n\t\t// replica sets from the larger to the smaller in size replica set. Scaling direction\n\t\t// drives what happens in case we are trying to scale replica sets of the same size.\n\t\t// In such a case when scaling up, we should scale up newer replica sets first, and\n\t\t// when scaling down, we should scale down older replica sets first.\n\t\tvar scalingOperation string\n\t\tswitch {\n\t\tcase deploymentReplicasToAdd > 0:\n\t\t\tsort.Sort(controller.ReplicaSetsBySizeNewer(allRSs))\n\t\t\tscalingOperation = \"up\"\n\n\t\tcase deploymentReplicasToAdd < 0:\n\t\t\tsort.Sort(controller.ReplicaSetsBySizeOlder(allRSs))\n\t\t\tscalingOperation = \"down\"\n\t\t}\n\n\t\t// Iterate over all active replica sets and estimate proportions for each of them.\n\t\t// The absolute value of deploymentReplicasAdded should never exceed the absolute\n\t\t// value of deploymentReplicasToAdd.\n\t\tdeploymentReplicasAdded := int32(0)\n\t\tnameToSize := make(map[string]int32)\n\t\tlogger := klog.FromContext(ctx)\n\t\tfor i := range allRSs {\n\t\t\trs := allRSs[i]\n\n\t\t\t// Estimate proportions if we have replicas to add, otherwise simply populate\n\t\t\t// nameToSize with the current sizes for each replica set.\n\t\t\tif deploymentReplicasToAdd != 0 {\n\t\t\t\tproportion := deploymentutil.GetProportion(logger, rs, *deployment, deploymentReplicasToAdd, deploymentReplicasAdded)\n\n\t\t\t\tnameToSize[rs.Name] = *(rs.Spec.Replicas) + proportion\n\t\t\t\tdeploymentReplicasAdded += proportion\n\t\t\t} else {\n\t\t\t\tnameToSize[rs.Name] = *(rs.Spec.Replicas)\n\t\t\t}\n\t\t}\n\n\t\t// Update all replica sets\n\t\tfor i := range allRSs {\n\t\t\trs := allRSs[i]\n\n\t\t\t// Add/remove any leftovers to the largest replica set.\n\t\t\tif i == 0 && deploymentReplicasToAdd != 0 {\n\t\t\t\tleftover := deploymentReplicasToAdd - deploymentReplicasAdded\n\t\t\t\tnameToSize[rs.Name] = nameToSize[rs.Name] + leftover\n\t\t\t\tif nameToSize[rs.Name] < 0 {\n\t\t\t\t\tnameToSize[rs.Name] = 0\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// TODO: Use transactions when we have them.\n\t\t\tif _, _, err := dc.scaleReplicaSet(ctx, rs, nameToSize[rs.Name], deployment, scalingOperation); err != nil {\n\t\t\t\t// Return as soon as we fail, the deployment is requeued\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (v *Vertex) scale(factor float64) {\n\tv.X = v.X * factor\n\tv.Y = v.Y * factor\n}", "func (self *Rectangle) Scale(x int) *Rectangle{\n return &Rectangle{self.Object.Call(\"scale\", x)}\n}", "func scale_pixel(x, y int) (float64, float64) {\n\tnewx := float64(x)/(float64(maxX)/3) - 2.0\n\tnewy := float64(y)/(float64(maxY)/2) - 0.0 \n\treturn newx, newy\n}", "func (k Keeper) MintCoins(ctx sdk.Context, moduleName string, amt *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.Minter) {\n\t\tpanic(sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, \"module account %s does not have permissions to mint tokens\", moduleName))\n\t}\n\n\t_, err := k.bk.IssueCoinPower(ctx, acc.GetID(), *amt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tk.Logger(ctx).Info(fmt.Sprintf(\"minted %s from %s module account\", amt.String(), moduleName))\n\n\treturn nil\n}", "func Scale(p point, factor int) point {\n\treturn point{p.x * factor, p.y * factor, p.z * factor}\n}", "func (c BaseController) MoveCoins(store weave.KVStore,\n\tsrc weave.Address, dest weave.Address, amount coin.Coin) error {\n\n\tif amount.IsZero() {\n\t\treturn errors.Wrap(errors.ErrAmount, \"zero value\")\n\t}\n\tif !amount.IsPositive() {\n\t\treturn errors.Wrapf(errors.ErrAmount, \"non-positive SendMsg: %#v\", &amount)\n\t}\n\n\t// load sender, subtract funds, and save\n\tsender, err := c.bucket.Get(store, src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif sender == nil {\n\t\treturn errors.Wrapf(errors.ErrEmpty, \"empty account %s\", src)\n\t}\n\tif !AsCoins(sender).Contains(amount) {\n\t\treturn errors.Wrap(errors.ErrAmount, \"funds\")\n\t}\n\terr = Subtract(AsCoinage(sender), amount)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = c.bucket.Save(store, sender)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// load/create recipient, add funds, save\n\trecipient, err := c.bucket.GetOrCreate(store, dest)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = Add(AsCoinage(recipient), amount)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn c.bucket.Save(store, recipient)\n}", "func (r Rectangle) Scale(factor float64) Rectangle {\n\treturn Rectangle{\n\t\tMin: r.Min.Mul(factor),\n\t\tMax: r.Max.Mul(factor),\n\t}\n}", "func (proof *PaymentProofV2) SetOutputCoins(v []coin.Coin) error {\n\tvar err error\n\tproof.outputCoins = make([]*coin.CoinV2, len(v))\n\tfor i := 0; i < len(v); i += 1 {\n\t\tproof.outputCoins[i] = new(coin.CoinV2)\n\t\tb := v[i].Bytes()\n\t\tif err = proof.outputCoins[i].SetBytes(b); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (g *GameObject) SetScale(scale float64) {\r\n\tg.Hitbox.maxX *= scale / g.Scale\r\n\tg.Hitbox.maxY *= scale / g.Scale\r\n\tg.Scale = scale\r\n}", "func (k Keeper) BurnCoinsForChallenges(ctx sdk.Ctx, relays int64, toAddr sdk.Address) {\n\tk.posKeeper.BurnForChallenge(ctx, sdk.NewInt(relays), toAddr)\n}", "func (dcr *ExchangeWallet) addInputCoins(msgTx *wire.MsgTx, coins asset.Coins) (uint64, error) {\n\tvar totalIn uint64\n\tfor _, coin := range coins {\n\t\top, err := dcr.convertCoin(coin)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tif op.value == 0 {\n\t\t\treturn 0, fmt.Errorf(\"zero-valued output detected for %s:%d\", op.txHash(), op.vout())\n\t\t}\n\t\ttotalIn += op.value\n\t\tprevOut := op.wireOutPoint()\n\t\ttxIn := wire.NewTxIn(prevOut, int64(op.value), []byte{})\n\t\tmsgTx.AddTxIn(txIn)\n\t}\n\treturn totalIn, nil\n}", "func (s *Service) scale(replicas int) {\n\tlog.WithField(\"replicas\", replicas).Debug(\"Service scaling\")\n\ts.state = StateScaling\n\tif s.CurrentReplicas != replicas {\n\t\ts.auklet.scaleService(s.ServiceID, replicas)\n\t\ts.auklet.Lock()\n\t\ts.auklet.metrics[MetricServiceScaleEventsTotal].(prometheus.Counter).Inc()\n\t\tif replicas > s.CurrentReplicas {\n\t\t\ts.auklet.serviceMetrics[s.ServiceID][MetricScaleUpEventsCount].(prometheus.Counter).Inc()\n\t\t} else {\n\t\t\ts.auklet.serviceMetrics[s.ServiceID][MetricScaleDownEventsCount].(prometheus.Counter).Inc()\n\t\t}\n\t\ts.auklet.Unlock()\n\t}\n\n\t// after scaling return to stable state\n\ts.stable()\n}", "func coinChange(coins []int, amount int) int {\n\t// let a(i, j) be the result for first i coins to get j amount.\n\t// then a(i, j) = min( a(i-1, j), a(i, j-coins[i])+1)\n\t// base case a(i, 0)=0, a(i, coins[i])=1\n\tif amount == 0 {\n\t\treturn 0\n\t}\n\ta0 := make([]int, amount+1)\n\ta1 := make([]int, amount+1)\n\tfor i := 0; i < len(coins); i++ {\n\t\ta1[0] = 0 // a(i, 0) = 0\n\t\tfor j := 1; j <= amount; j++ {\n\t\t\tif j == coins[i] {\n\t\t\t\ta1[j] = 1 // a(i, coins[i]) = 1\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ta1[j] = a0[j] // a(i, j) = a(i-1, j)\n\t\t\tif j-coins[i] > 0 && a1[j-coins[i]] > 0 {\n\t\t\t\tif a0[j] == 0 || a1[j-coins[i]]+1 < a0[j] {\n\t\t\t\t\ta1[j] = a1[j-coins[i]] + 1\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t//fmt.Println(a1)\n\t\ta0, a1 = a1, a0\n\t}\n\tif a0[amount] == 0 {\n\t\treturn -1\n\t}\n\treturn a0[amount]\n}", "func (p *Point) Scale(v float64) {\n\tp.x *= v\n\tp.y *= v\n}", "func uscale(bytes uint64) (scaled int64, scale string) {\n\ti := 0\n\tfor bytes > 1023 {\n\t\ti++\n\t\tbytes = bytes >> 10\n\t}\n\treturn int64(bytes), unitPrefixs[i]\n}", "func (dcr *ExchangeWallet) addInputCoins(msgTx *wire.MsgTx, coins asset.Coins) (uint64, error) {\n\tvar totalIn uint64\n\tfor _, coin := range coins {\n\t\top, err := dcr.convertCoin(coin)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tif op.value == 0 {\n\t\t\treturn 0, fmt.Errorf(\"zero-valued output detected for %s:%d\", op.txHash(), op.vout())\n\t\t}\n\t\tif op.tree == wire.TxTreeUnknown { // Set the correct prevout tree if unknown.\n\t\t\tunspentPrevOut, err := dcr.wallet.UnspentOutput(dcr.ctx, op.txHash(), op.vout(), op.tree)\n\t\t\tif err != nil {\n\t\t\t\treturn 0, fmt.Errorf(\"unable to determine tree for prevout %s: %v\", op.pt, err)\n\t\t\t}\n\t\t\top.tree = unspentPrevOut.Tree\n\t\t}\n\t\ttotalIn += op.value\n\t\tprevOut := op.wireOutPoint()\n\t\ttxIn := wire.NewTxIn(prevOut, int64(op.value), []byte{})\n\t\tmsgTx.AddTxIn(txIn)\n\t}\n\treturn totalIn, nil\n}", "func TestDecimal_Scale(t *testing.T) {\n\ta := New(1234, -3)\n\tif a.Scale() != -3 {\n\t\tt.Errorf(\"error\")\n\t}\n}", "func (w *windowImpl) Scale(dr image.Rectangle, src screen.Texture, sr image.Rectangle, op draw.Op, opts *screen.DrawOptions) {\n\tpanic(\"not implemented\") // TODO: Implement\n}", "func (self *ComponentScaleMinMax) SetScaleMinMax(minX interface{}, minY interface{}, maxX interface{}, maxY interface{}) {\n self.Object.Call(\"setScaleMinMax\", minX, minY, maxX, maxY)\n}", "func scale(n int) string {\n\tswitch n {\n\tcase 1:\n\t\treturn \"Celcius\"\n\tcase 2:\n\t\treturn \"Fahrenheit\"\n\tdefault:\n\t\treturn \"\"\n\t}\n}", "func Change(amount int) map[int]int {\n\tusedCoins := map[int]int{25: 0, 10: 0, 5: 0, 1: 0}\n\n\tif amount == 0 {\n\t\treturn usedCoins\n\t}\n\n\tremain := amount\n\n\tfor _, coin := range coins {\n\t\tif remain == 0 {\n\t\t\treturn usedCoins\n\t\t}\n\n\t\tmod := remain % coin\n\t\tif mod != remain {\n\t\t\tusedCoins[coin] = int(remain / coin)\n\t\t\tremain = mod\n\t\t}\n\t}\n\n\treturn usedCoins\n}" ]
[ "0.53646266", "0.5312407", "0.5284086", "0.5185207", "0.51215756", "0.50750524", "0.5065373", "0.50019264", "0.49968642", "0.49823198", "0.49739826", "0.48987997", "0.4869174", "0.48599055", "0.4815493", "0.48011187", "0.47879016", "0.47696072", "0.47589323", "0.47524524", "0.47524124", "0.47338954", "0.46928", "0.46884242", "0.4672732", "0.46711504", "0.46469107", "0.46466094", "0.46434674", "0.4632861", "0.4632501", "0.46298173", "0.4629572", "0.46288264", "0.46010748", "0.45794138", "0.45748407", "0.4549467", "0.4549313", "0.45438683", "0.45384747", "0.45303962", "0.45238942", "0.451829", "0.45029402", "0.44626173", "0.44610244", "0.44574344", "0.4448427", "0.44392017", "0.44345808", "0.44313297", "0.44290796", "0.44281232", "0.4420486", "0.4417458", "0.44163188", "0.4407654", "0.44073337", "0.43749264", "0.43722826", "0.43633652", "0.43608886", "0.4347979", "0.43368405", "0.4333907", "0.4331032", "0.4319784", "0.43092752", "0.43044642", "0.42930454", "0.4272178", "0.42508784", "0.42473167", "0.42461073", "0.4234278", "0.4229713", "0.42251295", "0.42188358", "0.42171898", "0.420896", "0.42082766", "0.42048904", "0.4199404", "0.41961703", "0.41953552", "0.41904944", "0.41844538", "0.4181977", "0.41809413", "0.41770405", "0.41757047", "0.4175097", "0.41732293", "0.41612554", "0.41608053", "0.41592807", "0.4157955", "0.4155872", "0.4149927" ]
0.8575942
0
NewClawbackRewardAction returns an exported.RewardAction for a ClawbackVestingAccount.
NewClawbackRewardAction возвращает экспортированный RewardAction для ClawbackVestingAccount.
func NewClawbackRewardAction(ak AccountKeeper, bk BankKeeper, sk StakingKeeper) exported.RewardAction { return clawbackRewardAction{ ak: ak, bk: bk, sk: sk, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewClawbackAction(requestor, dest sdk.AccAddress, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) exported.ClawbackAction {\n\treturn clawbackAction{\n\t\trequestor: requestor,\n\t\tdest: dest,\n\t\tak: ak,\n\t\tbk: bk,\n\t\tsk: sk,\n\t}\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 NewBcBotAction(j *bot.Jobs) *BcBotAction {\n\t// client := resty.New()\n\t// client.\n\t// \tSetRetryCount(3).\n\t// \tSetRetryWaitTime(10 * time.Second)\n\treturn &BcBotAction{jobs: j, client: nil, mutex: new(sync.RWMutex)}\n}", "func NewRecvAction(args any) *Action {\n\treturn &Action{Args: args}\n}", "func (cra clawbackRewardAction) ProcessReward(ctx sdk.Context, reward sdk.Coins, rawAccount exported.VestingAccount) error {\n\tcva, ok := rawAccount.(*ClawbackVestingAccount)\n\tif !ok {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrNotSupported, \"expected *ClawbackVestingAccount, got %T\", rawAccount)\n\t}\n\tcva.postReward(ctx, reward, cra.ak, cra.bk, cra.sk)\n\treturn nil\n}", "func NewRollbackAction(kit kit.Kit, viper *viper.Viper,\n\tauthSvrCli pbauthserver.AuthClient, dataMgrCli pbdatamanager.DataManagerClient,\n\tgseControllerCli pbgsecontroller.GSEControllerClient,\n\treq *pb.RollbackReleaseReq, resp *pb.RollbackReleaseResp) *RollbackAction {\n\n\taction := &RollbackAction{\n\t\tkit: kit,\n\t\tviper: viper,\n\t\tauthSvrCli: authSvrCli,\n\t\tdataMgrCli: dataMgrCli,\n\t\tgseControllerCli: gseControllerCli,\n\t\treq: req,\n\t\tresp: resp,\n\t}\n\n\taction.resp.Result = true\n\taction.resp.Code = pbcommon.ErrCode_E_OK\n\taction.resp.Message = \"OK\"\n\n\treturn action\n}", "func NewCollateralizeAction(c *Collateralize, tx *types.Transaction, index int) *Action {\n\thash := tx.Hash()\n\tfromaddr := tx.From()\n\tcfg := c.GetAPI().GetConfig()\n\ttokenDb, err := account.NewAccountDB(cfg, tokenE.GetName(), pty.CCNYTokenName, c.GetStateDB())\n\tif err != nil {\n\t\tclog.Error(\"NewCollateralizeAction\", \"Get Account DB error\", \"error\", err)\n\t\treturn nil\n\t}\n\n\treturn &Action{\n\t\tcoinsAccount: c.GetCoinsAccount(), tokenAccount: tokenDb, db: c.GetStateDB(), localDB: c.GetLocalDB(),\n\t\ttxhash: hash, fromaddr: fromaddr, blocktime: c.GetBlockTime(), height: c.GetHeight(),\n\t\texecaddr: dapp.ExecAddress(string(tx.Execer)), difficulty: c.GetDifficulty(), index: index, Collateralize: c}\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 (va *ClawbackVestingAccount) PostReward(ctx sdk.Context, reward sdk.Coins, action exported.RewardAction) error {\n\treturn action.ProcessReward(ctx, reward, va)\n}", "func NewRecoverableAction(supervisor *Supervisor) *RecoverableAction {\n\tra := &RecoverableAction{\n\t\tactionChan: make(chan Action),\n\t\treplyChan: make(chan string, 5),\n\t\tsupervisor: supervisor,\n\t}\n\n\tra.heartbeat = NewHeartbeat(ra, 1e8)\n\n\tgo ra.backend()\n\n\treturn ra\n}", "func NewCheckmate(winner Colour) Outcome { return Outcome{Winner: winner, Reason: checkmate} }", "func GetReward(a Action, feedback Action) float64 {\n\tif a == feedback {\n\t\treturn 1\n\t}\n\treturn -1\n}", "func NewChallengeAction(msg *Message) (*ChallengeAction, error) {\n\taction := &ChallengeAction{*msg}\n\n\treturn action, nil\n}", "func NewAction(name string, arg interface{}) {\n\tDefaultActionRegistry.Post(name, arg)\n}", "func New() Action {\n\treturn &action{}\n}", "func (_Token *TokenCallerSession) BaseReward(index *big.Int) (*big.Int, *big.Int, *big.Int, error) {\n\treturn _Token.Contract.BaseReward(&_Token.CallOpts, index)\n}", "func (va ClawbackVestingAccount) postReward(ctx sdk.Context, reward sdk.Coins, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) {\n\t// Find the scheduled amount of vested and unvested staking tokens\n\tbondDenom := sk.BondDenom(ctx)\n\tvested := ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, ctx.BlockTime().Unix()).AmountOf(bondDenom)\n\tunvested := va.OriginalVesting.AmountOf(bondDenom).Sub(vested)\n\n\tif unvested.IsZero() {\n\t\t// no need to adjust the vesting schedule\n\t\treturn\n\t}\n\n\tif vested.IsZero() {\n\t\t// all staked tokens must be unvested\n\t\tva.distributeReward(ctx, ak, bondDenom, reward)\n\t\treturn\n\t}\n\n\t// Find current split of account balance on staking axis\n\tbonded := sk.GetDelegatorBonded(ctx, va.GetAddress())\n\tunbonding := sk.GetDelegatorUnbonding(ctx, va.GetAddress())\n\tdelegated := bonded.Add(unbonding)\n\n\t// discover what has been slashed and remove from delegated amount\n\toldDelegated := va.DelegatedVesting.AmountOf(bondDenom).Add(va.DelegatedFree.AmountOf(bondDenom))\n\tslashed := oldDelegated.Sub(intMin(oldDelegated, delegated))\n\tdelegated = delegated.Sub(intMin(delegated, slashed))\n\n\t// Prefer delegated tokens to be unvested\n\tunvested = intMin(unvested, delegated)\n\tvested = delegated.Sub(unvested)\n\n\t// Compute the unvested amount of reward and add to vesting schedule\n\tif unvested.IsZero() {\n\t\treturn\n\t}\n\tif vested.IsZero() {\n\t\tva.distributeReward(ctx, ak, bondDenom, reward)\n\t\treturn\n\t}\n\tunvestedRatio := unvested.ToDec().QuoTruncate(bonded.ToDec()) // round down\n\tunvestedReward := scaleCoins(reward, unvestedRatio)\n\tva.distributeReward(ctx, ak, bondDenom, unvestedReward)\n}", "func (va ClawbackVestingAccount) distributeReward(ctx sdk.Context, ak AccountKeeper, bondDenom string, reward sdk.Coins) {\n\tnow := ctx.BlockTime().Unix()\n\tt := va.StartTime\n\tfirstUnvestedPeriod := 0\n\tunvestedTokens := sdk.ZeroInt()\n\tfor i, period := range va.VestingPeriods {\n\t\tt += period.Length\n\t\tif t <= now {\n\t\t\tfirstUnvestedPeriod = i + 1\n\t\t\tcontinue\n\t\t}\n\t\tunvestedTokens = unvestedTokens.Add(period.Amount.AmountOf(bondDenom))\n\t}\n\n\trunningTotReward := sdk.NewCoins()\n\trunningTotStaking := sdk.ZeroInt()\n\tfor i := firstUnvestedPeriod; i < len(va.VestingPeriods); i++ {\n\t\tperiod := va.VestingPeriods[i]\n\t\trunningTotStaking = runningTotStaking.Add(period.Amount.AmountOf(bondDenom))\n\t\trunningTotRatio := runningTotStaking.ToDec().Quo(unvestedTokens.ToDec())\n\t\ttargetCoins := scaleCoins(reward, runningTotRatio)\n\t\tthisReward := targetCoins.Sub(runningTotReward)\n\t\trunningTotReward = targetCoins\n\t\tperiod.Amount = period.Amount.Add(thisReward...)\n\t\tva.VestingPeriods[i] = period\n\t}\n\n\tva.OriginalVesting = va.OriginalVesting.Add(reward...)\n\tak.SetAccount(ctx, &va)\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 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 New() *Action {\n\treturn &Action{}\n}", "func NewAction(app *buffalo.App) *Action {\n\tas := &Action{\n\t\tApp: app,\n\t\tModel: NewModel(),\n\t}\n\treturn as\n}", "func (va *ClawbackVestingAccount) clawback(ctx sdk.Context, dest sdk.AccAddress, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) error {\n\t// Compute the clawback based on the account state only, and update account\n\ttoClawBack := va.computeClawback(ctx.BlockTime().Unix())\n\tif toClawBack.IsZero() {\n\t\treturn nil\n\t}\n\taddr := va.GetAddress()\n\tbondDenom := sk.BondDenom(ctx)\n\n\t// Compute the clawback based on bank balance and delegation, and update account\n\tencumbered := va.GetVestingCoins(ctx.BlockTime())\n\tbondedAmt := sk.GetDelegatorBonded(ctx, addr)\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, addr)\n\tbonded := sdk.NewCoins(sdk.NewCoin(bondDenom, bondedAmt))\n\tunbonding := sdk.NewCoins(sdk.NewCoin(bondDenom, unbondingAmt))\n\tunbonded := bk.GetAllBalances(ctx, addr)\n\ttoClawBack = va.updateDelegation(encumbered, toClawBack, bonded, unbonding, unbonded)\n\n\t// Write now now so that the bank module sees unvested tokens are unlocked.\n\t// Note that all store writes are aborted if there is a panic, so there is\n\t// no danger in writing incomplete results.\n\tak.SetAccount(ctx, va)\n\n\t// Now that future vesting events (and associated lockup) are removed,\n\t// the balance of the account is unlocked and can be freely transferred.\n\tspendable := bk.SpendableCoins(ctx, addr)\n\ttoXfer := coinsMin(toClawBack, spendable)\n\terr := bk.SendCoins(ctx, addr, dest, toXfer)\n\tif err != nil {\n\t\treturn err // shouldn't happen, given spendable check\n\t}\n\ttoClawBack = toClawBack.Sub(toXfer)\n\n\t// We need to traverse the staking data structures to update the\n\t// vesting account bookkeeping, and to recover more funds if necessary.\n\t// Staking is the only way unvested tokens should be missing from the bank balance.\n\n\t// If we need more, transfer UnbondingDelegations.\n\twant := toClawBack.AmountOf(bondDenom)\n\tunbondings := sk.GetUnbondingDelegations(ctx, addr, math.MaxUint16)\n\tfor _, unbonding := range unbondings {\n\t\tvalAddr, err := sdk.ValAddressFromBech32(unbonding.ValidatorAddress)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\ttransferred := sk.TransferUnbonding(ctx, addr, dest, valAddr, want)\n\t\twant = want.Sub(transferred)\n\t\tif !want.IsPositive() {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// If we need more, transfer Delegations.\n\tif want.IsPositive() {\n\t\tdelegations := sk.GetDelegatorDelegations(ctx, addr, math.MaxUint16)\n\t\tfor _, delegation := range delegations {\n\t\t\tvalidatorAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err) // shouldn't happen\n\t\t\t}\n\t\t\tvalidator, found := sk.GetValidator(ctx, validatorAddr)\n\t\t\tif !found {\n\t\t\t\t// validator has been removed\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\twantShares, err := validator.SharesFromTokensTruncated(want)\n\t\t\tif err != nil {\n\t\t\t\t// validator has no tokens\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttransferredShares := sk.TransferDelegation(ctx, addr, dest, delegation.GetValidatorAddr(), wantShares)\n\t\t\t// to be conservative in what we're clawing back, round transferred shares up\n\t\t\ttransferred := validator.TokensFromSharesRoundUp(transferredShares).RoundInt()\n\t\t\twant = want.Sub(transferred)\n\t\t\tif !want.IsPositive() {\n\t\t\t\t// Could be slightly negative, due to rounding?\n\t\t\t\t// Don't think so, due to the precautions above.\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// If we've transferred everything and still haven't transferred the desired clawback amount,\n\t// then the account must have most some unvested tokens from slashing.\n\treturn nil\n}", "func NewAction() actions.Action {\n\treturn &Action{}\n}", "func NewAction() actions.Action {\n\treturn &Action{}\n}", "func (a Actor) AwardBlockReward(rt vmr.Runtime, params *AwardBlockRewardParams) *adt.EmptyValue {\n\trt.ValidateImmediateCallerIs(builtin.SystemActorAddr)\n\tAssertMsg(rt.CurrentBalance().GreaterThanEqual(params.GasReward),\n\t\t\"actor current balance %v insufficient to pay gas reward %v\", rt.CurrentBalance(), params.GasReward)\n\n\tAssertMsg(params.TicketCount > 0, \"cannot give block reward for zero tickets\")\n\n\tminer, ok := rt.ResolveAddress(params.Miner)\n\tif !ok {\n\t\trt.Abortf(exitcode.ErrIllegalState, \"failed to resolve given owner address\")\n\t}\n\n\tpriorBalance := rt.CurrentBalance()\n\n\tvar penalty abi.TokenAmount\n\tvar st State\n\trt.State().Transaction(&st, func() interface{} {\n\t\tblockReward := a.computeBlockReward(&st, big.Sub(priorBalance, params.GasReward), params.TicketCount)\n\t\ttotalReward := big.Add(blockReward, params.GasReward)\n\n\t\t// Cap the penalty at the total reward value.\n\t\tpenalty = big.Min(params.Penalty, totalReward)\n\n\t\t// Reduce the payable reward by the penalty.\n\t\trewardPayable := big.Sub(totalReward, penalty)\n\n\t\tAssertMsg(big.Add(rewardPayable, penalty).LessThanEqual(priorBalance),\n\t\t\t\"reward payable %v + penalty %v exceeds balance %v\", rewardPayable, penalty, priorBalance)\n\n\t\t// Record new reward into reward map.\n\t\tif rewardPayable.GreaterThan(abi.NewTokenAmount(0)) {\n\t\t\tnewReward := Reward{\n\t\t\t\tStartEpoch: rt.CurrEpoch(),\n\t\t\t\tEndEpoch: rt.CurrEpoch() + rewardVestingPeriod,\n\t\t\t\tValue: rewardPayable,\n\t\t\t\tAmountWithdrawn: abi.NewTokenAmount(0),\n\t\t\t\tVestingFunction: rewardVestingFunction,\n\t\t\t}\n\t\t\tif err := st.addReward(adt.AsStore(rt), miner, &newReward); err != nil {\n\t\t\t\trt.Abortf(exitcode.ErrIllegalState, \"failed to add reward to rewards map: %w\", err)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\n\t// Burn the penalty amount.\n\t_, code := rt.Send(builtin.BurntFundsActorAddr, builtin.MethodSend, nil, penalty)\n\tbuiltin.RequireSuccess(rt, code, \"failed to send penalty to BurntFundsActor\")\n\n\treturn nil\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 (_Token *TokenSession) BaseReward(index *big.Int) (*big.Int, *big.Int, *big.Int, error) {\n\treturn _Token.Contract.BaseReward(&_Token.CallOpts, index)\n}", "func NewAction() actions.Action {\n\treturn &action{}\n}", "func (_Token *TokenCaller) BaseReward(opts *bind.CallOpts, index *big.Int) (*big.Int, *big.Int, *big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t\tret1 = new(*big.Int)\n\t\tret2 = new(*big.Int)\n\t)\n\tout := &[]interface{}{\n\t\tret0,\n\t\tret1,\n\t\tret2,\n\t}\n\terr := _Token.contract.Call(opts, out, \"baseReward\", index)\n\treturn *ret0, *ret1, *ret2, err\n}", "func CreateAction(\n\tcmd, keyB, id, secretKey string,\n\targs ...interface{}) *types.Action {\n\n\tmac := hmac.New(sha1.New, []byte(secretKey))\n\tmac.Write([]byte(cmd))\n\tmac.Write([]byte(keyB))\n\tmac.Write([]byte(id))\n\tsum := mac.Sum(nil)\n\tsumhex := hex.EncodeToString(sum)\n\n\treturn &types.Action{\n\t\tCommand: cmd,\n\t\tStorageKey: keyB,\n\t\tArgs: args,\n\t\tId: id,\n\t\tSecret: sumhex,\n\t}\n}", "func CreateAction(r *Raptor) *Action {\n\treturn &Action{\n\t\tRaptor: r,\n\t}\n}", "func GetAction(client *whisk.Client, actionName string) func() (*whisk.Action, error) {\n\treturn func() (*whisk.Action, error) {\n\t\taction, _, err := client.Actions.Get(actionName, true)\n\t\tif err == nil {\n\t\t\treturn action, nil\n\t\t}\n\t\treturn nil, err\n\t}\n}", "func NewAction(t *Pos33Ticket, tx *types.Transaction) *Action {\n\thash := tx.Hash()\n\tfromaddr := tx.From()\n\treturn &Action{t.GetCoinsAccount(), t.GetStateDB(), hash, fromaddr,\n\t\tt.GetBlockTime(), t.GetHeight(), dapp.ExecAddress(string(tx.Execer)), t.GetAPI()}\n}", "func (x *fastReflection_MsgWithdrawDelegatorReward) New() protoreflect.Message {\n\treturn new(fastReflection_MsgWithdrawDelegatorReward)\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 NewActionAgent(\n\ttabletAlias topo.TabletAlias,\n\tdbcfgs *dbconfigs.DBConfigs,\n\tmycnf *mysqlctl.Mycnf,\n\tport, securePort int,\n\toverridesFile string,\n) (agent *ActionAgent, err error) {\n\tschemaOverrides := loadSchemaOverrides(overridesFile)\n\n\ttopoServer := topo.GetServer()\n\tmysqld := mysqlctl.NewMysqld(\"Dba\", mycnf, &dbcfgs.Dba, &dbcfgs.Repl)\n\n\tagent = &ActionAgent{\n\t\tTopoServer: topoServer,\n\t\tTabletAlias: tabletAlias,\n\t\tMysqld: mysqld,\n\t\tDBConfigs: dbcfgs,\n\t\tSchemaOverrides: schemaOverrides,\n\t\tdone: make(chan struct{}),\n\t\tHistory: history.New(historyLength),\n\t\tchangeItems: make(chan tabletChangeItem, 100),\n\t}\n\n\t// Start the binlog player services, not playing at start.\n\tagent.BinlogPlayerMap = NewBinlogPlayerMap(topoServer, &dbcfgs.App.ConnectionParams, mysqld)\n\tRegisterBinlogPlayerMap(agent.BinlogPlayerMap)\n\n\t// try to figure out the mysql port\n\tmysqlPort := mycnf.MysqlPort\n\tif mysqlPort == 0 {\n\t\t// we don't know the port, try to get it from mysqld\n\t\tvar err error\n\t\tmysqlPort, err = mysqld.GetMysqlPort()\n\t\tif err != nil {\n\t\t\tlog.Warningf(\"Cannot get current mysql port, will use 0 for now: %v\", err)\n\t\t}\n\t}\n\n\tif err := agent.Start(mysqlPort, port, securePort); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// register the RPC services from the agent\n\tagent.registerQueryService()\n\n\t// start health check if needed\n\tagent.initHeathCheck()\n\n\treturn agent, nil\n}", "func newBreachArbiter(wallet *lnwallet.LightningWallet, db *channeldb.DB,\n\tnotifier chainntnfs.ChainNotifier, h *htlcswitch.Switch,\n\tchain lnwallet.BlockChainIO, fe lnwallet.FeeEstimator) *breachArbiter {\n\n\treturn &breachArbiter{\n\t\twallet: wallet,\n\t\tdb: db,\n\t\tnotifier: notifier,\n\t\tchainIO: chain,\n\t\thtlcSwitch: h,\n\t\testimator: fe,\n\n\t\tbreachObservers: make(map[wire.OutPoint]chan struct{}),\n\t\tbreachedContracts: make(chan *retributionInfo),\n\t\tnewContracts: make(chan *lnwallet.LightningChannel),\n\t\tsettledContracts: make(chan *wire.OutPoint),\n\t\tquit: make(chan struct{}),\n\t}\n}", "func NewAction(payload interface{}) Action {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Error: %v\\n\", r)\n\t\t\tfmt.Fprintf(os.Stderr, \"Payload: %v\\n\", payload)\n\t\t}\n\t}()\n\n\tvar a Action\n\ta.payload = payload\n\ta.headers = make(map[string]string)\n\n\tfor k, v := range payload.(map[interface{}]interface{}) {\n\t\tswitch k {\n\t\tcase \"catch\":\n\t\t\ta.catch = v.(string)\n\t\tcase \"warnings\":\n\t\t\t// TODO\n\t\t\tcontinue\n\t\tcase \"allowed_warnings\":\n\t\t\t// TODO\n\t\t\tcontinue\n\t\tcase \"node_selector\":\n\t\t\tcontinue\n\t\tcase \"headers\":\n\t\t\tfor kk, vv := range v.(map[interface{}]interface{}) {\n\t\t\t\ta.headers[kk.(string)] = vv.(string)\n\t\t\t}\n\t\tdefault:\n\t\t\ta.method = k.(string)\n\t\t\ta.params = v.(map[interface{}]interface{})\n\t\t}\n\t}\n\n\treturn a\n}", "func (act *ActionTrace) Action() (*ActionTrace, error) {\n\treturn act, nil\n}", "func New() *Action {\n\treturn &Action{w: os.Stdout}\n}", "func (_Token *TokenCaller) CurrentReward(opts *bind.CallOpts, account common.Address) (struct {\n\tInitialDeposit *big.Int\n\tReward *big.Int\n}, error) {\n\tret := new(struct {\n\t\tInitialDeposit *big.Int\n\t\tReward *big.Int\n\t})\n\tout := ret\n\terr := _Token.contract.Call(opts, out, \"currentReward\", account)\n\treturn *ret, err\n}", "func NewAction(fn ActionFn) *Action {\n\treturn &Action{\n\t\tfn: fn,\n\t\tdoneCh: make(chan struct{}),\n\t}\n}", "func (t *trusteeImpl) NewMiningRewardTx(block consensus.Block) *consensus.Transaction {\n\tvar tx *consensus.Transaction\n\t// build list of miner nodes for uncle blocks\n\tuncleMiners := make([][]byte, len(block.UncleMiners()))\n\tfor i, uncleMiner := range block.UncleMiners() {\n\t\tuncleMiners[i] = uncleMiner\n\t}\n\t\n\tops := make([]Op, 1 + len(uncleMiners))\n\t// first add self's mining reward\n\tops[0] = *t.myReward\n\t\n\t// now add award for each uncle\n\tfor i, uncleMiner := range uncleMiners {\n\t\top := NewOp(OpReward)\n\t\top.Params[ParamUncle] = bytesToHexString(uncleMiner)\n\t\top.Params[ParamAward] = UncleAward\n\t\tops[i+1] = *op \n\t}\n\t// serialize ops into payload\n\tif payload,err := common.Serialize(ops); err != nil {\n\t\tt.log.Error(\"Failed to serialize ops into payload: %s\", err)\n\t\treturn nil\n\t} else {\n\t\t// make a signed transaction out of payload\n\t\tif signature := t.sign(payload); len(signature) > 0 {\n\t\t\t// return the signed transaction\n\t\t\ttx = consensus.NewTransaction(payload, signature, t.myAddress)\n\t\t\tblock.AddTransaction(tx)\n\t\t\tt.process(block, tx)\n\t\t}\n\t}\n\treturn tx\n}", "func NewEvictAction() Action {\n\treturn &evictAction{}\n}", "func NewAuthorizeAction(ctx context.Context, viper *viper.Viper, authMode string,\n\tlocalAuthController *local.Controller, bkiamAuthController *bkiam.Controller,\n\treq *pb.AuthorizeReq, resp *pb.AuthorizeResp) *AuthorizeAction {\n\n\taction := &AuthorizeAction{\n\t\tctx: ctx,\n\t\tviper: viper,\n\t\tauthMode: authMode,\n\t\tlocalAuthController: localAuthController,\n\t\tbkiamAuthController: bkiamAuthController,\n\t\treq: req,\n\t\tresp: resp,\n\t}\n\n\taction.resp.Seq = req.Seq\n\taction.resp.Code = pbcommon.ErrCode_E_OK\n\taction.resp.Message = \"OK\"\n\n\treturn action\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 (dm *DelveMode) RestAction() data.Action {\n\treturn func(e *data.Entity) {\n\t\te.NextTurn += 1\n\t}\n}", "func (ca clawbackAction) TakeFromAccount(ctx sdk.Context, rawAccount exported.VestingAccount) error {\n\tcva, ok := rawAccount.(*ClawbackVestingAccount)\n\tif !ok {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrNotSupported, \"clawback expects *ClawbackVestingAccount, got %T\", rawAccount)\n\t}\n\tif ca.requestor.String() != cva.FunderAddress {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, \"clawback can only be requested by original funder %s\", cva.FunderAddress)\n\t}\n\treturn cva.clawback(ctx, ca.dest, ca.ak, ca.bk, ca.sk)\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 (qiu *QueueItemUpdate) AddAction(i int) *QueueItemUpdate {\n\tqiu.mutation.AddAction(i)\n\treturn qiu\n}", "func NewStalemate() Outcome { return Outcome{Winner: Transparent, Reason: stalemate} }", "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 NewCheck() beekeeper.Action {\n\treturn &Check{}\n}", "func (_IStakingRewards *IStakingRewardsTransactor) GetReward(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _IStakingRewards.contract.Transact(opts, \"getReward\")\n}", "func NewShowAction() *ShowAction {\n\treturn &ShowAction{}\n}", "func (_Smartchef *SmartchefTransactor) StopReward(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _Smartchef.contract.Transact(opts, \"stopReward\")\n}", "func NewEventRuleAction() *EventRuleAction {\n\tthis := EventRuleAction{}\n\tvar actionTaken WafRuleAction = \"BLOCK\"\n\tthis.ActionTaken = &actionTaken\n\tvar requestType EventWafRequestType = \"CHALLENGE\"\n\tthis.RequestType = &requestType\n\tvar result RuleActionResultType = \"RESULT_TYPE_UNSPECIFIED\"\n\tthis.Result = &result\n\treturn &this\n}", "func NewActionInspect(target ID, cost time.Duration) *ActionInspect {\n\treturn &ActionInspect{\n\t\t// FIXME: Figure out the actual base costs of inspection.\n\t\tAction: Action{\n\t\t\tchannel: cost / 4,\n\t\t\trecovery: cost - cost/4,\n\t\t},\n\t\tTarget: target,\n\t}\n}", "func MakeReweigh(db *pop.Connection, assertions Assertions) models.Reweigh {\n\tshipment := assertions.MTOShipment\n\tif isZeroUUID(shipment.ID) {\n\t\tassertions.MTOShipment.Status = models.MTOShipmentStatusApproved\n\t\tshipment = MakeMTOShipment(db, assertions)\n\t}\n\n\treweigh := models.Reweigh{\n\t\tRequestedAt: time.Now(),\n\t\tRequestedBy: models.ReweighRequesterTOO,\n\t\tShipment: shipment,\n\t\tShipmentID: shipment.ID,\n\t}\n\n\tmergeModels(&reweigh, assertions.Reweigh)\n\n\tmustCreate(db, &reweigh, assertions.Stub)\n\n\treturn reweigh\n}", "func (x *fastReflection_MsgWithdrawDelegatorRewardResponse) New() protoreflect.Message {\n\treturn new(fastReflection_MsgWithdrawDelegatorRewardResponse)\n}", "func (_Token *TokenCallerSession) CurrentReward(account common.Address) (struct {\n\tInitialDeposit *big.Int\n\tReward *big.Int\n}, error) {\n\treturn _Token.Contract.CurrentReward(&_Token.CallOpts, account)\n}", "func (_SweetToken *SweetTokenTransactor) Burn(opts *bind.TransactOpts, wad *big.Int) (*types.Transaction, error) {\n\treturn _SweetToken.contract.Transact(opts, \"burn\", wad)\n}", "func (s *MutableState) AddRewards(time epochtime.EpochTime, factor *quantity.Quantity, accounts []signature.PublicKey) error {\n\tsteps, err := s.RewardSchedule()\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar activeStep *staking.RewardStep\n\tfor _, step := range steps {\n\t\tif time < step.Until {\n\t\t\tactiveStep = &step\n\t\t\tbreak\n\t\t}\n\t}\n\tif activeStep == nil {\n\t\t// We're past the end of the schedule.\n\t\treturn nil\n\t}\n\n\tcommonPool, err := s.CommonPool()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"loading common pool\")\n\t}\n\n\tfor _, id := range accounts {\n\t\tent := s.Account(id)\n\n\t\tq := ent.Escrow.Active.Balance.Clone()\n\t\t// Multiply first.\n\t\tif err := q.Mul(factor); err != nil {\n\t\t\treturn errors.Wrap(err, \"multiplying by reward factor\")\n\t\t}\n\t\tif err := q.Mul(&activeStep.Scale); err != nil {\n\t\t\treturn errors.Wrap(err, \"multiplying by reward step scale\")\n\t\t}\n\t\tif err := q.Quo(staking.RewardAmountDenominator); err != nil {\n\t\t\treturn errors.Wrap(err, \"dividing by reward amount denominator\")\n\t\t}\n\n\t\tif q.IsZero() {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar com *quantity.Quantity\n\t\trate := ent.Escrow.CommissionSchedule.CurrentRate(time)\n\t\tif rate != nil {\n\t\t\tcom = q.Clone()\n\t\t\t// Multiply first.\n\t\t\tif err := com.Mul(rate); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"multiplying by commission rate\")\n\t\t\t}\n\t\t\tif err := com.Quo(staking.CommissionRateDenominator); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"dividing by commission rate denominator\")\n\t\t\t}\n\n\t\t\tif err := q.Sub(com); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"subtracting commission\")\n\t\t\t}\n\t\t}\n\n\t\tif !q.IsZero() {\n\t\t\tif err := quantity.Move(&ent.Escrow.Active.Balance, commonPool, q); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"transferring to active escrow balance from common pool\")\n\t\t\t}\n\t\t}\n\n\t\tif com != nil && !com.IsZero() {\n\t\t\tdelegation := s.Delegation(id, id)\n\n\t\t\tif err := ent.Escrow.Active.Deposit(&delegation.Shares, commonPool, com); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"depositing commission\")\n\t\t\t}\n\n\t\t\ts.SetDelegation(id, id, delegation)\n\t\t}\n\n\t\ts.SetAccount(id, ent)\n\t}\n\n\ts.SetCommonPool(commonPool)\n\n\treturn nil\n}", "func (c *Coinbase) AddReward(output *Output) {\n\toutput.EncryptedMask = make([]byte, 1)\n\tc.Rewards = append(c.Rewards, output)\n}", "func (_Smartchef *SmartchefTransactorSession) StopReward() (*types.Transaction, error) {\n\treturn _Smartchef.Contract.StopReward(&_Smartchef.TransactOpts)\n}", "func (_Token *TokenSession) CurrentReward(account common.Address) (struct {\n\tInitialDeposit *big.Int\n\tReward *big.Int\n}, error) {\n\treturn _Token.Contract.CurrentReward(&_Token.CallOpts, account)\n}", "func NewRewardTx(coinbase common.Address, reward *big.Int, timestamp uint64) (*types.Transaction, error) {\n\tif err := validateReward(reward); err != nil {\n\t\treturn nil, err\n\t}\n\n\ttxData := types.TransactionData{\n\t\tType: types.TxTypeReward,\n\t\tFrom: common.EmptyAddress,\n\t\tTo: coinbase,\n\t\tAmount: new(big.Int).Set(reward),\n\t\tGasPrice: common.Big0,\n\t\tTimestamp: timestamp,\n\t\tPayload: emptyPayload,\n\t}\n\n\ttx := types.Transaction{\n\t\tHash: crypto.MustHash(txData),\n\t\tData: txData,\n\t\tSignature: emptySig,\n\t}\n\n\treturn &tx, nil\n}", "func (qiuo *QueueItemUpdateOne) AddAction(i int) *QueueItemUpdateOne {\n\tqiuo.mutation.AddAction(i)\n\treturn qiuo\n}", "func NewAction(name string) *Action {\n\ta := &Action{\n\t\tName: name,\n\t\tEnabled: true,\n\t}\n\treturn a\n}", "func (_SweetToken *SweetTokenTransactorSession) Burn(wad *big.Int) (*types.Transaction, error) {\n\treturn _SweetToken.Contract.Burn(&_SweetToken.TransactOpts, wad)\n}", "func NewLogAction() Action {\n\treturn &logAction{}\n}", "func toAction(actionInput string) (GameAction, error) {\n\tnormalised := strings.ToUpper(strings.TrimSuffix(actionInput, \"\\n\"))\n\tif len(normalised) < 1 {\n\t\treturn -1, errors.New(\"No action specified\")\n\t}\n\n\tswitch normalised[0] {\n\tcase 'E':\n\t\treturn Explore, nil\n\n\tcase 'F':\n\t\treturn Flag, nil\n\n\tdefault:\n\t\treturn -1, errors.New(\"Invalid action\")\n\t}\n}", "func CreateBackupAction(service *pgCommon.PostgresServiceInformations) action.IAction {\n\treturn action.FormAction{\n\t\tName: \"Backup\",\n\t\tUniqueCommand: \"cmd_pg_create_backup\",\n\t\tPlaceholder: nil,\n\t\tActionExecuteCallback: func(placeholder interface{}) (interface{}, error) {\n\t\t\treturn nil, CreateBackup(service)\n\t\t},\n\t}\n}", "func (ra *RecoverableAction) Action(action Action) string {\n\tra.actionChan <- action\n\n\treturn <-ra.replyChan\n}", "func (a *Agent) Action(state, goal *tensor.Dense) (action int, err error) {\n\ta.steps++\n\tdefer func() { a.epsilon.Set(a.Epsilon.Value()) }()\n\tif rand.Float64() < a.epsilon.Scalar() {\n\t\t// explore\n\t\taction, err = a.env.SampleAction()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tlog.Infov(\"taking random action\", action)\n\t\treturn\n\t}\n\taction, err = a.action(state, goal)\n\tlog.Infov(\"taking action\", action)\n\treturn\n}", "func CreateAction(action func(*cli.Context) error) func(*cli.Context) error {\n\treturn func(c *cli.Context) error {\n\t\terr := action(c)\n\t\tif err != nil {\n\t\t\tiocli.Error(\"%s\", err)\n\t\t}\n\n\t\treturn nil\n\t}\n}", "func (_Smartchef *SmartchefSession) StopReward() (*types.Transaction, error) {\n\treturn _Smartchef.Contract.StopReward(&_Smartchef.TransactOpts)\n}", "func (_IERC20Minter *IERC20MinterTransactor) Burn(opts *bind.TransactOpts, amount *big.Int) (*types.Transaction, error) {\n\treturn _IERC20Minter.contract.Transact(opts, \"burn\", amount)\n}", "func (_IStakingRewards *IStakingRewardsTransactorSession) GetReward() (*types.Transaction, error) {\n\treturn _IStakingRewards.Contract.GetReward(&_IStakingRewards.TransactOpts)\n}", "func (_XStaking *XStakingTransactor) GetReward(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _XStaking.contract.Transact(opts, \"getReward\")\n}", "func claim(args []string) (string, error) {\n\tamount, err := util.StringToRau(args[0], util.IotxDecimalNum)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tpayload := make([]byte, 0)\n\tif len(args) == 2 {\n\t\tpayload = []byte(args[1])\n\t}\n\tsender, err := alias.Address(signer)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif gasLimit == 0 {\n\t\tgasLimit = action.ClaimFromRewardingFundBaseGas +\n\t\t\taction.ClaimFromRewardingFundGasPerByte*uint64(len(payload))\n\t}\n\tvar gasPriceRau *big.Int\n\tif len(gasPrice) == 0 {\n\t\tgasPriceRau, err = GetGasPrice()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t} else {\n\t\tgasPriceRau, err = util.StringToRau(gasPrice, util.GasPriceDecimalNum)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\tif nonce == 0 {\n\t\taccountMeta, err := account.GetAccountMeta(sender)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tnonce = accountMeta.PendingNonce\n\t}\n\tb := &action.ClaimFromRewardingFundBuilder{}\n\tact := b.SetAmount(amount).SetData(payload).Build()\n\tbd := &action.EnvelopeBuilder{}\n\telp := bd.SetNonce(nonce).\n\t\tSetGasPrice(gasPriceRau).\n\t\tSetGasLimit(gasLimit).\n\t\tSetAction(&act).Build()\n\treturn sendAction(elp)\n}", "func NewDrawByAgreement() Outcome { return Outcome{Winner: Transparent, Reason: drawByAgreement} }", "func ActionFromInt(st int) Action {\n\tact := Action{}\n\tif st%2 == 1 {\n\t\tact.PlayRecent = true\n\t}\n\n\tst = (st & 0xF) >> 1\n\t// Now st is the TargetPlayerOffset or SelectedCard. We don't know which, but if *any* card was selected,\n\t// then the other player must be targeted (since the played card is a guard), so for 2 players the offset is 1.\n\tif st > 0 {\n\t\tact.TargetPlayerOffset = 1\n\t}\n\tact.SelectedCard = Card(st + 1)\n\treturn act\n}", "func NewAction(cmd Command) Action {\n\tswitch cmd.name {\n\tcase buildCommand:\n\t\treturn NewBuildAction(afero.NewOsFs(), cmd.helmRepoName, cmd.artifactsPath)\n\tdefault:\n\t\treturn ShowAction{}\n\t}\n}", "func (_DetailedTestToken *DetailedTestTokenTransactorSession) Burn(_from common.Address, _amount *big.Int) (*types.Transaction, error) {\n\treturn _DetailedTestToken.Contract.Burn(&_DetailedTestToken.TransactOpts, _from, _amount)\n}", "func (b *AccessReviewRequestBuilder) Action(value string) *AccessReviewRequestBuilder {\n\tb.action = value\n\tb.bitmap_ |= 2\n\treturn b\n}", "func (c RewardsController) CollectReward(id string) revel.Result {\n\tif !c.GetCurrentUser() {\n\t\treturn c.ForbiddenResponse()\n\t}\n\n\tif !bson.IsObjectIdHex(id) {\n\t\treturn c.ErrorResponse(nil, c.Message(\"error.invalid\", \"\"), core.ModelStatus[core.StatusInvalidID])\n\t}\n\n\tvar selector = []bson.M{\n\t\tbson.M{\"user_id\": c.CurrentUser.GetID().Hex()},\n\t\tbson.M{\"_id\": id},\n\t\tbson.M{\"multi\": false},\n\t}\n\tvar query = bson.M{\"$set\": []bson.M{\n\t\tbson.M{\"status.name\": core.StatusObtained},\n\t\tbson.M{\"status.code\": core.ValidationStatus[core.StatusObtained]},\n\t}}\n\n\t// Get pending Rewards for the user\n\tif Reward, ok := app.Mapper.GetModel(&models.Reward{}); ok {\n\t\tif err := Reward.UpdateQuery(selector, query, false); err != nil {\n\t\t\trevel.ERROR.Print(\"ERROR Find\")\n\t\t\treturn c.ErrorResponse(err, err.Error(), 400)\n\t\t}\n\t\treturn c.SuccessResponse(bson.M{\"data\": \"Reward collected successfully\"}, \"success\", core.ModelsType[core.ModelSimpleResponse], nil)\n\t}\n\n\treturn c.ServerErrorResponse()\n}", "func (s SubTransaction) ForwardAction() Action {\n\treturn s.forward\n}", "func Create(\n\tcontext contexts.Contextable,\n\tlogger *logger.Logger,\n\tconnection *golastic.Connection,\n\tqueue *notifications.Queue,\n\tctx context.Context,\n) (Actionable, error) {\n\taction, err := build(context.Action())\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := action.Init(context, logger, connection, queue, ctx); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := action.ApplyOptions().ApplyFilters(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn action, nil\n}", "func (_SweetToken *SweetTokenSession) Burn(wad *big.Int) (*types.Transaction, error) {\n\treturn _SweetToken.Contract.Burn(&_SweetToken.TransactOpts, wad)\n}", "func ViewReward(rw http.ResponseWriter, r *http.Request) {\n\t// get the token\n\treqToken := r.Header.Get(\"Authorization\")\n\t\n\t// get the claims\n\tclaims, isNotValid := GetClaims(reqToken, rw)\n\tif isNotValid {\n\t\treturn\n\t}\n\n\tdt, err := db.GetUserRewards(claims.Roll)\n\tif err != nil {\n\t\trw.WriteHeader(http.StatusInternalServerError)\n\t\trw.Write(Rsp(err.Error(), \"Server Error\"))\n\t\treturn\n\t}\n\trw.WriteHeader(http.StatusOK)\n\tres := c.RespData{\n\t\tMessage: \"All data\",\n\t\tData: dt,\n\t}\n\tjson.NewEncoder(rw).Encode(res)\n}", "func (a *ReturnTrolleyAction) DeepCopyAction() Action {\n\treturn a.DeepCopy()\n}", "func NewEventRuleActionWithDefaults() *EventRuleAction {\n\tthis := EventRuleAction{}\n\tvar actionTaken WafRuleAction = \"BLOCK\"\n\tthis.ActionTaken = &actionTaken\n\tvar requestType EventWafRequestType = \"CHALLENGE\"\n\tthis.RequestType = &requestType\n\tvar result RuleActionResultType = \"RESULT_TYPE_UNSPECIFIED\"\n\tthis.Result = &result\n\treturn &this\n}", "func MiningRewardBalance(block consensus.Block, account []byte) *RTU {\n//\tif bytes, err := block.Lookup([]byte(bytesToHexString(account))); err == nil {\n\tif bytes, err := block.Lookup(account); err == nil {\n\t\treturn BytesToRtu(bytes)\n\t}\n\treturn BytesToRtu(nil)\n}", "func (_XStaking *XStakingTransactorSession) GetReward() (*types.Transaction, error) {\n\treturn _XStaking.Contract.GetReward(&_XStaking.TransactOpts)\n}", "func NewWithWriter(w io.Writer) *Action {\n\treturn &Action{w: w}\n}", "func NewOutcomeNotCompleted() Outcome { return Outcome{Winner: Transparent, Reason: notCompleted} }", "func NewListAction(model store.ProjectModel) *ListAction {\n\treturn &ListAction{\n\t\tmodel: model,\n\t}\n}", "func (_DetailedTestToken *DetailedTestTokenTransactor) Burn(opts *bind.TransactOpts, _from common.Address, _amount *big.Int) (*types.Transaction, error) {\n\treturn _DetailedTestToken.contract.Transact(opts, \"burn\", _from, _amount)\n}" ]
[ "0.7404201", "0.6953166", "0.5464461", "0.53948647", "0.5364549", "0.52774936", "0.5242982", "0.51873976", "0.5161824", "0.51156837", "0.5114475", "0.5087842", "0.5044298", "0.4955228", "0.49131867", "0.48881137", "0.4860685", "0.48492974", "0.48389384", "0.48261693", "0.48073062", "0.4806934", "0.47948968", "0.47775978", "0.47775978", "0.47685742", "0.4763258", "0.47577775", "0.4755035", "0.4744198", "0.47240314", "0.47206163", "0.47000334", "0.46924087", "0.46889618", "0.4676094", "0.46661752", "0.46485558", "0.45820913", "0.4581459", "0.45421323", "0.4524639", "0.4506681", "0.4499991", "0.44623595", "0.44439712", "0.44408196", "0.44202092", "0.44117185", "0.437283", "0.43673515", "0.43633744", "0.43479988", "0.43374288", "0.43325737", "0.43264967", "0.4321511", "0.43210125", "0.43131346", "0.43083677", "0.42984998", "0.42921782", "0.42878333", "0.42831647", "0.4270413", "0.42682657", "0.42569688", "0.42564178", "0.42544532", "0.42497995", "0.42399403", "0.423938", "0.42342055", "0.42323777", "0.42239317", "0.42190844", "0.42179886", "0.42167017", "0.4210979", "0.42095917", "0.41938713", "0.41894215", "0.4184966", "0.4183407", "0.41826695", "0.41709533", "0.41607255", "0.41501132", "0.41435888", "0.41435602", "0.41292846", "0.4124662", "0.412181", "0.41193622", "0.41142455", "0.4112855", "0.41126797", "0.4112431", "0.41072062", "0.4106683" ]
0.8147421
0
ProcessReward implements the exported.RewardAction interface.
ProcessReward реализует интерфейс exported.RewardAction.
func (cra clawbackRewardAction) ProcessReward(ctx sdk.Context, reward sdk.Coins, rawAccount exported.VestingAccount) error { cva, ok := rawAccount.(*ClawbackVestingAccount) if !ok { return sdkerrors.Wrapf(sdkerrors.ErrNotSupported, "expected *ClawbackVestingAccount, got %T", rawAccount) } cva.postReward(ctx, reward, cra.ak, cra.bk, cra.sk) return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "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 (c RewardsController) CollectReward(id string) revel.Result {\n\tif !c.GetCurrentUser() {\n\t\treturn c.ForbiddenResponse()\n\t}\n\n\tif !bson.IsObjectIdHex(id) {\n\t\treturn c.ErrorResponse(nil, c.Message(\"error.invalid\", \"\"), core.ModelStatus[core.StatusInvalidID])\n\t}\n\n\tvar selector = []bson.M{\n\t\tbson.M{\"user_id\": c.CurrentUser.GetID().Hex()},\n\t\tbson.M{\"_id\": id},\n\t\tbson.M{\"multi\": false},\n\t}\n\tvar query = bson.M{\"$set\": []bson.M{\n\t\tbson.M{\"status.name\": core.StatusObtained},\n\t\tbson.M{\"status.code\": core.ValidationStatus[core.StatusObtained]},\n\t}}\n\n\t// Get pending Rewards for the user\n\tif Reward, ok := app.Mapper.GetModel(&models.Reward{}); ok {\n\t\tif err := Reward.UpdateQuery(selector, query, false); err != nil {\n\t\t\trevel.ERROR.Print(\"ERROR Find\")\n\t\t\treturn c.ErrorResponse(err, err.Error(), 400)\n\t\t}\n\t\treturn c.SuccessResponse(bson.M{\"data\": \"Reward collected successfully\"}, \"success\", core.ModelsType[core.ModelSimpleResponse], nil)\n\t}\n\n\treturn c.ServerErrorResponse()\n}", "func GetReward(a Action, feedback Action) float64 {\n\tif a == feedback {\n\t\treturn 1\n\t}\n\treturn -1\n}", "func (c *Coinbase) AddReward(output *Output) {\n\toutput.EncryptedMask = make([]byte, 1)\n\tc.Rewards = append(c.Rewards, output)\n}", "func (va *ClawbackVestingAccount) PostReward(ctx sdk.Context, reward sdk.Coins, action exported.RewardAction) error {\n\treturn action.ProcessReward(ctx, reward, va)\n}", "func (a Actor) AwardBlockReward(rt vmr.Runtime, params *AwardBlockRewardParams) *adt.EmptyValue {\n\trt.ValidateImmediateCallerIs(builtin.SystemActorAddr)\n\tAssertMsg(rt.CurrentBalance().GreaterThanEqual(params.GasReward),\n\t\t\"actor current balance %v insufficient to pay gas reward %v\", rt.CurrentBalance(), params.GasReward)\n\n\tAssertMsg(params.TicketCount > 0, \"cannot give block reward for zero tickets\")\n\n\tminer, ok := rt.ResolveAddress(params.Miner)\n\tif !ok {\n\t\trt.Abortf(exitcode.ErrIllegalState, \"failed to resolve given owner address\")\n\t}\n\n\tpriorBalance := rt.CurrentBalance()\n\n\tvar penalty abi.TokenAmount\n\tvar st State\n\trt.State().Transaction(&st, func() interface{} {\n\t\tblockReward := a.computeBlockReward(&st, big.Sub(priorBalance, params.GasReward), params.TicketCount)\n\t\ttotalReward := big.Add(blockReward, params.GasReward)\n\n\t\t// Cap the penalty at the total reward value.\n\t\tpenalty = big.Min(params.Penalty, totalReward)\n\n\t\t// Reduce the payable reward by the penalty.\n\t\trewardPayable := big.Sub(totalReward, penalty)\n\n\t\tAssertMsg(big.Add(rewardPayable, penalty).LessThanEqual(priorBalance),\n\t\t\t\"reward payable %v + penalty %v exceeds balance %v\", rewardPayable, penalty, priorBalance)\n\n\t\t// Record new reward into reward map.\n\t\tif rewardPayable.GreaterThan(abi.NewTokenAmount(0)) {\n\t\t\tnewReward := Reward{\n\t\t\t\tStartEpoch: rt.CurrEpoch(),\n\t\t\t\tEndEpoch: rt.CurrEpoch() + rewardVestingPeriod,\n\t\t\t\tValue: rewardPayable,\n\t\t\t\tAmountWithdrawn: abi.NewTokenAmount(0),\n\t\t\t\tVestingFunction: rewardVestingFunction,\n\t\t\t}\n\t\t\tif err := st.addReward(adt.AsStore(rt), miner, &newReward); err != nil {\n\t\t\t\trt.Abortf(exitcode.ErrIllegalState, \"failed to add reward to rewards map: %w\", err)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\n\t// Burn the penalty amount.\n\t_, code := rt.Send(builtin.BurntFundsActorAddr, builtin.MethodSend, nil, penalty)\n\tbuiltin.RequireSuccess(rt, code, \"failed to send penalty to BurntFundsActor\")\n\n\treturn nil\n}", "func EstimateReward(reward, pr, gamma float64) float64 {\n\tret := reward / (pr + gamma)\n\tlog.Logf(MABLogLevel, \"MAB Estimate Reward: %v / (%v + %v) = %v\\n\",\n\t\treward, pr, gamma, ret)\n\treturn ret\n}", "func (s *BlocksService) Reward(ctx context.Context) (*BlocksReward, *http.Response, error) {\n\tvar responseStruct *BlocksReward\n\tresp, err := s.client.SendRequest(ctx, \"GET\", \"blocks/getReward\", nil, &responseStruct)\n\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn responseStruct, resp, err\n}", "func (_Token *TokenCallerSession) BaseReward(index *big.Int) (*big.Int, *big.Int, *big.Int, error) {\n\treturn _Token.Contract.BaseReward(&_Token.CallOpts, index)\n}", "func (_Token *TokenCaller) BaseReward(opts *bind.CallOpts, index *big.Int) (*big.Int, *big.Int, *big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t\tret1 = new(*big.Int)\n\t\tret2 = new(*big.Int)\n\t)\n\tout := &[]interface{}{\n\t\tret0,\n\t\tret1,\n\t\tret2,\n\t}\n\terr := _Token.contract.Call(opts, out, \"baseReward\", index)\n\treturn *ret0, *ret1, *ret2, err\n}", "func (d *Dao) AddReward(c context.Context, iRewardID int64, uid int64, iSource int64, iRoomid int64, iLifespan int64) (err error) {\n\t//aReward, _ := getRewardConfByLid(iRewardID)\n\n\tm, _ := time.ParseDuration(fmt.Sprintf(\"+%dh\", iLifespan))\n\n\targ := &AnchorTaskModel.AnchorReward{\n\t\tUid: uid,\n\t\tRewardId: iRewardID,\n\t\tRoomid: iRoomid,\n\t\tSource: iSource,\n\t\tAchieveTime: xtime.Time(time.Now().Unix()),\n\t\tExpireTime: xtime.Time(time.Now().Add(m).Unix()),\n\t\tStatus: model.RewardUnUsed,\n\t}\n\n\t//spew.Dump\n\t// (arg)\n\tif err := d.orm.Create(arg).Error; err != nil {\n\t\tlog.Error(\"addReward(%v) error(%v)\", arg, err)\n\t\treturn err\n\t}\n\n\tif err := d.SetNewReward(c, uid, int64(1)); err != nil {\n\t\tlog.Error(\"addRewardMc(%v) error(%v)\", uid, err)\n\t}\n\n\tif err := d.SetHasReward(c, uid, int64(1)); err != nil {\n\t\tlog.Error(\"SetHasReward(%v) error(%v)\", uid, err)\n\t}\n\n\tlog.Info(\"addReward (%v) succ\", arg)\n\n\treturn\n}", "func (k Querier) Rewards(c context.Context, req *types.QueryRewardsRequest) (*types.QueryRewardsResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"invalid request\")\n\t}\n\n\tif req.StakingCoinDenom != \"\" {\n\t\tif err := sdk.ValidateDenom(req.StakingCoinDenom); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tctx := sdk.UnwrapSDKContext(c)\n\tstore := ctx.KVStore(k.storeKey)\n\tvar rewards []types.Reward\n\tvar pageRes *query.PageResponse\n\tvar err error\n\n\tif req.Farmer != \"\" {\n\t\tvar farmerAcc sdk.AccAddress\n\t\tfarmerAcc, err = sdk.AccAddressFromBech32(req.Farmer)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tstorePrefix := types.GetRewardsByFarmerIndexKey(farmerAcc)\n\t\tindexStore := prefix.NewStore(store, storePrefix)\n\t\tpageRes, err = query.FilteredPaginate(indexStore, req.Pagination, func(key, value []byte, accumulate bool) (bool, error) {\n\t\t\t_, stakingCoinDenom := types.ParseRewardsByFarmerIndexKey(append(storePrefix, key...))\n\t\t\tif req.StakingCoinDenom != \"\" {\n\t\t\t\tif stakingCoinDenom != req.StakingCoinDenom {\n\t\t\t\t\treturn false, nil\n\t\t\t\t}\n\t\t\t}\n\t\t\treward, found := k.GetReward(ctx, stakingCoinDenom, farmerAcc)\n\t\t\tif !found { // TODO: remove this check\n\t\t\t\treturn false, fmt.Errorf(\"reward not found\")\n\t\t\t}\n\t\t\tif accumulate {\n\t\t\t\trewards = append(rewards, reward)\n\t\t\t}\n\t\t\treturn true, nil\n\t\t})\n\t} else {\n\t\tvar storePrefix []byte\n\t\tif req.StakingCoinDenom != \"\" {\n\t\t\tstorePrefix = types.GetRewardsByStakingCoinDenomKey(req.StakingCoinDenom)\n\t\t} else {\n\t\t\tstorePrefix = types.RewardKeyPrefix\n\t\t}\n\t\trewardStore := prefix.NewStore(store, storePrefix)\n\n\t\tpageRes, err = query.Paginate(rewardStore, req.Pagination, func(key, value []byte) error {\n\t\t\tstakingCoinDenom, farmerAcc := types.ParseRewardKey(append(storePrefix, key...))\n\t\t\trewardCoins, err := k.UnmarshalRewardCoins(value)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\trewards = append(rewards, types.Reward{\n\t\t\t\tFarmer: farmerAcc.String(),\n\t\t\t\tStakingCoinDenom: stakingCoinDenom,\n\t\t\t\tRewardCoins: rewardCoins.RewardCoins,\n\t\t\t})\n\t\t\treturn nil\n\t\t})\n\t}\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &types.QueryRewardsResponse{Rewards: rewards, Pagination: pageRes}, nil\n}", "func ViewReward(rw http.ResponseWriter, r *http.Request) {\n\t// get the token\n\treqToken := r.Header.Get(\"Authorization\")\n\t\n\t// get the claims\n\tclaims, isNotValid := GetClaims(reqToken, rw)\n\tif isNotValid {\n\t\treturn\n\t}\n\n\tdt, err := db.GetUserRewards(claims.Roll)\n\tif err != nil {\n\t\trw.WriteHeader(http.StatusInternalServerError)\n\t\trw.Write(Rsp(err.Error(), \"Server Error\"))\n\t\treturn\n\t}\n\trw.WriteHeader(http.StatusOK)\n\tres := c.RespData{\n\t\tMessage: \"All data\",\n\t\tData: dt,\n\t}\n\tjson.NewEncoder(rw).Encode(res)\n}", "func (_Token *TokenSession) BaseReward(index *big.Int) (*big.Int, *big.Int, *big.Int, error) {\n\treturn _Token.Contract.BaseReward(&_Token.CallOpts, index)\n}", "func (node *TreeNode) backpropagateReward(scores [2]float64) {\n\tcurrentNode := node\n\tfor currentNode.Parent != nil {\n\t\tcurrentNode.VisitCount += 1.0\n\t\tcurrentNode.CumulativeScore[0] += scores[0]\n\t\tcurrentNode.CumulativeScore[1] += scores[1]\n\t\tcurrentNode = currentNode.Parent\n\t}\n\t//Increment root node counter\n\tcurrentNode.VisitCount += 1.0\n}", "func (d *Dao) UseReward(id int64, usePlat string) (rst bool, err error) {\n\tif err := d.orm.\n\t\tModel(&model.AnchorReward{}).\n\t\tWhere(\"id=?\", id).\n\t\tUpdate(map[string]interface{}{\"status\": model.RewardUsed, \"use_plat\": usePlat, \"use_time\": xtime.Time(time.Now().Unix())}).Error; err != nil {\n\t\tlog.Error(\"useReward (%v) error(%v)\", id, err)\n\t\treturn rst, err\n\t}\n\trst = true\n\treturn\n}", "func accumulateRewards(config *params.ChainConfig, state *state.DB, header *types.Header) {\n\t// TODO: implement mining rewards\n}", "func (va ClawbackVestingAccount) distributeReward(ctx sdk.Context, ak AccountKeeper, bondDenom string, reward sdk.Coins) {\n\tnow := ctx.BlockTime().Unix()\n\tt := va.StartTime\n\tfirstUnvestedPeriod := 0\n\tunvestedTokens := sdk.ZeroInt()\n\tfor i, period := range va.VestingPeriods {\n\t\tt += period.Length\n\t\tif t <= now {\n\t\t\tfirstUnvestedPeriod = i + 1\n\t\t\tcontinue\n\t\t}\n\t\tunvestedTokens = unvestedTokens.Add(period.Amount.AmountOf(bondDenom))\n\t}\n\n\trunningTotReward := sdk.NewCoins()\n\trunningTotStaking := sdk.ZeroInt()\n\tfor i := firstUnvestedPeriod; i < len(va.VestingPeriods); i++ {\n\t\tperiod := va.VestingPeriods[i]\n\t\trunningTotStaking = runningTotStaking.Add(period.Amount.AmountOf(bondDenom))\n\t\trunningTotRatio := runningTotStaking.ToDec().Quo(unvestedTokens.ToDec())\n\t\ttargetCoins := scaleCoins(reward, runningTotRatio)\n\t\tthisReward := targetCoins.Sub(runningTotReward)\n\t\trunningTotReward = targetCoins\n\t\tperiod.Amount = period.Amount.Add(thisReward...)\n\t\tva.VestingPeriods[i] = period\n\t}\n\n\tva.OriginalVesting = va.OriginalVesting.Add(reward...)\n\tak.SetAccount(ctx, &va)\n}", "func (_Contract *ContractCaller) TaskHandlingReward(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Contract.contract.Call(opts, &out, \"taskHandlingReward\")\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 (_Lmc *LmcCaller) GetUserAccumulatedReward(opts *bind.CallOpts, _userAddress common.Address, tokenIndex *big.Int) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Lmc.contract.Call(opts, &out, \"getUserAccumulatedReward\", _userAddress, tokenIndex)\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 (_XStaking *XStakingFilterer) FilterRewardPaid(opts *bind.FilterOpts, user []common.Address) (*XStakingRewardPaidIterator, error) {\n\n\tvar userRule []interface{}\n\tfor _, userItem := range user {\n\t\tuserRule = append(userRule, userItem)\n\t}\n\n\tlogs, sub, err := _XStaking.contract.FilterLogs(opts, \"RewardPaid\", userRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &XStakingRewardPaidIterator{contract: _XStaking.contract, event: \"RewardPaid\", logs: logs, sub: sub}, nil\n}", "func (s *MutableState) AddRewardSingleAttenuated(time epochtime.EpochTime, factor *quantity.Quantity, attenuationNumerator, attenuationDenominator int, account signature.PublicKey) error {\n\tsteps, err := s.RewardSchedule()\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar activeStep *staking.RewardStep\n\tfor _, step := range steps {\n\t\tif time < step.Until {\n\t\t\tactiveStep = &step\n\t\t\tbreak\n\t\t}\n\t}\n\tif activeStep == nil {\n\t\t// We're past the end of the schedule.\n\t\treturn nil\n\t}\n\n\tvar numQ, denQ quantity.Quantity\n\tif err = numQ.FromInt64(int64(attenuationNumerator)); err != nil {\n\t\treturn errors.Wrapf(err, \"importing attenuation numerator %d\", attenuationNumerator)\n\t}\n\tif err = denQ.FromInt64(int64(attenuationDenominator)); err != nil {\n\t\treturn errors.Wrapf(err, \"importing attenuation denominator %d\", attenuationDenominator)\n\t}\n\n\tcommonPool, err := s.CommonPool()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"loading common pool\")\n\t}\n\n\tent := s.Account(account)\n\n\tq := ent.Escrow.Active.Balance.Clone()\n\t// Multiply first.\n\tif err := q.Mul(factor); err != nil {\n\t\treturn errors.Wrap(err, \"multiplying by reward factor\")\n\t}\n\tif err := q.Mul(&activeStep.Scale); err != nil {\n\t\treturn errors.Wrap(err, \"multiplying by reward step scale\")\n\t}\n\tif err := q.Mul(&numQ); err != nil {\n\t\treturn errors.Wrap(err, \"multiplying by attenuation numerator\")\n\t}\n\tif err := q.Quo(staking.RewardAmountDenominator); err != nil {\n\t\treturn errors.Wrap(err, \"dividing by reward amount denominator\")\n\t}\n\tif err := q.Quo(&denQ); err != nil {\n\t\treturn errors.Wrap(err, \"dividing by attenuation denominator\")\n\t}\n\n\tif q.IsZero() {\n\t\treturn nil\n\t}\n\n\tvar com *quantity.Quantity\n\trate := ent.Escrow.CommissionSchedule.CurrentRate(time)\n\tif rate != nil {\n\t\tcom = q.Clone()\n\t\t// Multiply first.\n\t\tif err := com.Mul(rate); err != nil {\n\t\t\treturn errors.Wrap(err, \"multiplying by commission rate\")\n\t\t}\n\t\tif err := com.Quo(staking.CommissionRateDenominator); err != nil {\n\t\t\treturn errors.Wrap(err, \"dividing by commission rate denominator\")\n\t\t}\n\n\t\tif err := q.Sub(com); err != nil {\n\t\t\treturn errors.Wrap(err, \"subtracting commission\")\n\t\t}\n\t}\n\n\tif !q.IsZero() {\n\t\tif err := quantity.Move(&ent.Escrow.Active.Balance, commonPool, q); err != nil {\n\t\t\treturn errors.Wrap(err, \"transferring to active escrow balance from common pool\")\n\t\t}\n\t}\n\n\tif com != nil && !com.IsZero() {\n\t\tdelegation := s.Delegation(account, account)\n\n\t\tif err := ent.Escrow.Active.Deposit(&delegation.Shares, commonPool, com); err != nil {\n\t\t\treturn errors.Wrap(err, \"depositing commission\")\n\t\t}\n\n\t\ts.SetDelegation(account, account, delegation)\n\t}\n\n\ts.SetAccount(account, ent)\n\n\ts.SetCommonPool(commonPool)\n\n\treturn nil\n}", "func (_XStaking *XStakingFilterer) FilterRewardAdded(opts *bind.FilterOpts) (*XStakingRewardAddedIterator, error) {\n\n\tlogs, sub, err := _XStaking.contract.FilterLogs(opts, \"RewardAdded\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &XStakingRewardAddedIterator{contract: _XStaking.contract, event: \"RewardAdded\", logs: logs, sub: sub}, nil\n}", "func (_IStakingRewards *IStakingRewardsTransactor) GetReward(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _IStakingRewards.contract.Transact(opts, \"getReward\")\n}", "func ValidateRewardTx(tx *types.Transaction, header *types.BlockHeader) error {\n\tif tx.Data.Type != types.TxTypeReward || !tx.Data.From.IsEmpty() || tx.Data.AccountNonce != 0 || tx.Data.GasPrice.Cmp(common.Big0) != 0 || tx.Data.GasLimit != 0 || len(tx.Data.Payload) != 0 {\n\t\treturn errInvalidReward\n\t}\n\n\t// validate to address\n\tto := tx.Data.To\n\tif to.IsEmpty() {\n\t\treturn errEmptyToAddress\n\t}\n\n\tif !to.Equal(header.Creator) {\n\t\treturn errCoinbaseMismatch\n\t}\n\n\t// validate reward\n\tamount := tx.Data.Amount\n\tif err := validateReward(amount); err != nil {\n\t\treturn err\n\t}\n\n\treward := consensus.GetReward(header.Height)\n\tif reward == nil || reward.Cmp(amount) != 0 {\n\t\treturn fmt.Errorf(\"invalid reward Amount, block height %d, want %s, got %s\", header.Height, reward, amount)\n\t}\n\n\t// validate timestamp\n\tif tx.Data.Timestamp != header.CreateTimestamp.Uint64() {\n\t\treturn errTimestampMismatch\n\t}\n\n\treturn nil\n}", "func (_Smartchef *SmartchefTransactor) StopReward(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _Smartchef.contract.Transact(opts, \"stopReward\")\n}", "func (_XStaking *XStakingCaller) Rewards(opts *bind.CallOpts, arg0 common.Address) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _XStaking.contract.Call(opts, &out, \"rewards\", arg0)\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 (as AccountStorage) SetReward(ctx sdk.Context, accKey types.AccountKey, reward *Reward) sdk.Error {\n\tstore := ctx.KVStore(as.key)\n\trewardByte, err := as.cdc.MarshalJSON(*reward)\n\tif err != nil {\n\t\treturn ErrFailedToMarshalReward(err)\n\t}\n\tstore.Set(getRewardKey(accKey), rewardByte)\n\treturn nil\n}", "func (_Lmc *LmcCallerSession) GetUserAccumulatedReward(_userAddress common.Address, tokenIndex *big.Int) (*big.Int, error) {\n\treturn _Lmc.Contract.GetUserAccumulatedReward(&_Lmc.CallOpts, _userAddress, tokenIndex)\n}", "func (t *Transaction) Reward() string {\n\treturn t.reward\n}", "func (_XStaking *XStakingTransactor) GetReward(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _XStaking.contract.Transact(opts, \"getReward\")\n}", "func (_Smartchef *SmartchefCaller) PendingReward(opts *bind.CallOpts, _user common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Smartchef.contract.Call(opts, out, \"pendingReward\", _user)\n\treturn *ret0, err\n}", "func (_Lmc *LmcSession) GetUserAccumulatedReward(_userAddress common.Address, tokenIndex *big.Int) (*big.Int, error) {\n\treturn _Lmc.Contract.GetUserAccumulatedReward(&_Lmc.CallOpts, _userAddress, tokenIndex)\n}", "func (m *EntitlementLootBoxReward) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (c4 *Connect4) GetReward() int {\n\tif c4.Winner == nil {\n\t\treturn 0\n\t} else if *c4.Winner == 1 {\n\t\treturn 1\n\t}\n\treturn -1\n}", "func computeReward(epoch abi.ChainEpoch, prevTheta, currTheta, simpleTotal, baselineTotal big.Int) abi.TokenAmount {\n\tsimpleReward := big.Mul(simpleTotal, ExpLamSubOne) //Q.0 * Q.128 => Q.128\n\tepochLam := big.Mul(big.NewInt(int64(epoch)), Lambda) // Q.0 * Q.128 => Q.128\n\n\tsimpleReward = big.Mul(simpleReward, big.NewFromGo(math.ExpNeg(epochLam.Int))) // Q.128 * Q.128 => Q.256\n\tsimpleReward = big.Rsh(simpleReward, math.Precision128) // Q.256 >> 128 => Q.128\n\n\tbaselineReward := big.Sub(computeBaselineSupply(currTheta, baselineTotal), computeBaselineSupply(prevTheta, baselineTotal)) // Q.128\n\n\treward := big.Add(simpleReward, baselineReward) // Q.128\n\n\treturn big.Rsh(reward, math.Precision128) // Q.128 => Q.0\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactor) DistributeETHReward(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.contract.Transact(opts, \"distributeETHReward\")\n}", "func (_Token *TokenCaller) CurrentReward(opts *bind.CallOpts, account common.Address) (struct {\n\tInitialDeposit *big.Int\n\tReward *big.Int\n}, error) {\n\tret := new(struct {\n\t\tInitialDeposit *big.Int\n\t\tReward *big.Int\n\t})\n\tout := ret\n\terr := _Token.contract.Call(opts, out, \"currentReward\", account)\n\treturn *ret, err\n}", "func (k Keeper) DeleteReward(ctx sdk.Context, stakingCoinDenom string, farmerAcc sdk.AccAddress) {\n\tstore := ctx.KVStore(k.storeKey)\n\tstore.Delete(types.GetRewardKey(stakingCoinDenom, farmerAcc))\n\tstore.Delete(types.GetRewardByFarmerAndStakingCoinDenomIndexKey(farmerAcc, stakingCoinDenom))\n}", "func (k Keeper) ClaimEarnReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tsyncedClaim, found := k.GetSynchronizedEarnClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr := k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetEarnClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func (k Keeper) ClaimUSDXMintingReward(ctx sdk.Context, owner, receiver sdk.AccAddress, multiplierName string) error {\n\tclaim, found := k.GetUSDXMintingClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, types.USDXMintingRewardDenom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", types.USDXMintingRewardDenom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tclaim, err := k.SynchronizeUSDXMintingClaim(ctx, claim)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trewardAmount := sdk.NewDecFromInt(claim.Reward.Amount).Mul(multiplier.Factor).RoundInt()\n\tif rewardAmount.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\trewardCoin := sdk.NewCoin(claim.Reward.Denom, rewardAmount)\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr = k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, sdk.NewCoins(rewardCoin), length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tk.ZeroUSDXMintingClaim(ctx, claim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claim.Reward.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, claim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func (k Keeper) ClaimSwapReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tsyncedClaim, found := k.GetSynchronizedSwapClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr := k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetSwapClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func (_IStakingRewards *IStakingRewardsTransactorSession) GetReward() (*types.Transaction, error) {\n\treturn _IStakingRewards.Contract.GetReward(&_IStakingRewards.TransactOpts)\n}", "func rewardAndSlash(ctx contract.Context, cachedDelegations *CachedDposStorage, state *State) ([]*DelegationResult, error) {\n\tformerValidatorTotals := make(map[string]loom.BigUInt)\n\tdelegatorRewards := make(map[string]*loom.BigUInt)\n\tdistributedRewards := common.BigZero()\n\n\tdelegations, err := cachedDelegations.loadDelegationList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, validator := range state.Validators {\n\t\tcandidate := GetCandidateByPubKey(ctx, validator.PubKey)\n\n\t\tif candidate == nil {\n\t\t\tctx.Logger().Info(\"Attempted to reward validator no longer on candidates list.\", \"validator\", validator)\n\t\t\tcontinue\n\t\t}\n\n\t\tcandidateAddress := loom.UnmarshalAddressPB(candidate.Address)\n\t\tvalidatorKey := candidateAddress.String()\n\t\tstatistic, _ := GetStatistic(ctx, candidateAddress)\n\n\t\tif statistic == nil {\n\t\t\tdelegatorRewards[validatorKey] = common.BigZero()\n\t\t\tformerValidatorTotals[validatorKey] = *common.BigZero()\n\t\t} else {\n\t\t\t// If a validator is jailed, don't calculate and distribute rewards\n\t\t\tif ctx.FeatureEnabled(features.DPOSVersion3_3, false) {\n\t\t\t\tif statistic.Jailed {\n\t\t\t\t\tdelegatorRewards[validatorKey] = common.BigZero()\n\t\t\t\t\tformerValidatorTotals[validatorKey] = *common.BigZero()\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\t// If a validator's SlashPercentage is 0, the validator is\n\t\t\t// rewarded for avoiding faults during the last slashing period\n\t\t\tif common.IsZero(statistic.SlashPercentage.Value) {\n\t\t\t\tdistributionTotal := calculateRewards(statistic.DelegationTotal.Value, state.Params, state.TotalValidatorDelegations.Value)\n\n\t\t\t\t// The validator share, equal to validator_fee * total_validotor_reward\n\t\t\t\t// is to be split between the referrers and the validator\n\t\t\t\tvalidatorShare := CalculateFraction(loom.BigUInt{big.NewInt(int64(candidate.Fee))}, distributionTotal)\n\n\t\t\t\t// delegatorsShare is what fraction of the total rewards will be\n\t\t\t\t// distributed to delegators\n\t\t\t\tdelegatorsShare := common.BigZero()\n\t\t\t\tdelegatorsShare.Sub(&distributionTotal, &validatorShare)\n\t\t\t\tdelegatorRewards[validatorKey] = delegatorsShare\n\n\t\t\t\t// Distribute rewards to referrers\n\t\t\t\tfor _, d := range delegations {\n\t\t\t\t\tif loom.UnmarshalAddressPB(d.Validator).Compare(loom.UnmarshalAddressPB(candidate.Address)) == 0 {\n\t\t\t\t\t\tdelegation, err := GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\t\t\t\t\t// if the delegation is not found OR if the delegation\n\t\t\t\t\t\t// has no referrer, we do not need to attempt to\n\t\t\t\t\t\t// distribute the referrer rewards\n\t\t\t\t\t\tif err == contract.ErrNotFound || len(delegation.Referrer) == 0 {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t} else if err != nil {\n\t\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// if referrer is not found, do not distribute the reward\n\t\t\t\t\t\treferrerAddress := getReferrer(ctx, delegation.Referrer)\n\t\t\t\t\t\tif referrerAddress == nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// calculate referrerReward\n\t\t\t\t\t\treferrerReward := calculateRewards(delegation.Amount.Value, state.Params, state.TotalValidatorDelegations.Value)\n\t\t\t\t\t\treferrerReward = CalculateFraction(loom.BigUInt{big.NewInt(int64(candidate.Fee))}, referrerReward)\n\t\t\t\t\t\treferrerReward = CalculateFraction(defaultReferrerFee, referrerReward)\n\n\t\t\t\t\t\t// referrer fees are delegater to limbo validator\n\t\t\t\t\t\tdistributedRewards.Add(distributedRewards, &referrerReward)\n\t\t\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, LimboValidatorAddress(ctx).MarshalPB(), referrerAddress, referrerReward)\n\n\t\t\t\t\t\t// any referrer bonus amount is subtracted from the validatorShare\n\t\t\t\t\t\tvalidatorShare.Sub(&validatorShare, &referrerReward)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tdistributedRewards.Add(distributedRewards, &validatorShare)\n\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, candidate.Address, candidate.Address, validatorShare)\n\n\t\t\t\t// If a validator has some non-zero WhitelistAmount,\n\t\t\t\t// calculate the validator's reward based on whitelist amount\n\t\t\t\tif !common.IsZero(statistic.WhitelistAmount.Value) {\n\t\t\t\t\tamount := calculateWeightedWhitelistAmount(*statistic)\n\t\t\t\t\twhitelistDistribution := calculateShare(amount, statistic.DelegationTotal.Value, *delegatorsShare)\n\t\t\t\t\t// increase a delegator's distribution\n\t\t\t\t\tdistributedRewards.Add(distributedRewards, &whitelistDistribution)\n\t\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, candidate.Address, candidate.Address, whitelistDistribution)\n\t\t\t\t}\n\n\t\t\t\t// Keeping track of cumulative distributed rewards by adding\n\t\t\t\t// every validator's total rewards to\n\t\t\t\t// `state.TotalRewardDistribution`\n\t\t\t\t// NOTE: because we round down in every `calculateRewards` call,\n\t\t\t\t// we expect `state.TotalRewardDistribution` to be a slight\n\t\t\t\t// overestimate of what was actually distributed. We could be\n\t\t\t\t// exact with our record keeping by incrementing\n\t\t\t\t// `state.TotalRewardDistribution` each time\n\t\t\t\t// `IncreaseRewardDelegation` is called, but because we will not\n\t\t\t\t// use `state.TotalRewardDistributions` as part of any invariants,\n\t\t\t\t// we will live with this situation.\n\t\t\t\tif !ctx.FeatureEnabled(features.DPOSVersion3_1, false) {\n\t\t\t\t\tstate.TotalRewardDistribution.Value.Add(&state.TotalRewardDistribution.Value, &distributionTotal)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif err := slashValidatorDelegations(ctx, cachedDelegations, statistic, candidateAddress); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tif err := SetStatistic(ctx, statistic); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tformerValidatorTotals[validatorKey] = statistic.DelegationTotal.Value\n\t\t}\n\t}\n\n\tnewDelegationTotals, err := distributeDelegatorRewards(ctx, cachedDelegations, formerValidatorTotals, delegatorRewards, distributedRewards)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif ctx.FeatureEnabled(features.DPOSVersion3_1, false) {\n\t\tstate.TotalRewardDistribution.Value.Add(&state.TotalRewardDistribution.Value, distributedRewards)\n\t}\n\n\tdelegationResults := make([]*DelegationResult, 0, len(newDelegationTotals))\n\tfor validator := range newDelegationTotals {\n\t\tdelegationResults = append(delegationResults, &DelegationResult{\n\t\t\tValidatorAddress: loom.MustParseAddress(validator),\n\t\t\tDelegationTotal: *newDelegationTotals[validator],\n\t\t})\n\t}\n\tsort.Sort(byDelegationTotal(delegationResults))\n\n\treturn delegationResults, nil\n}", "func (s *MutableState) AddRewards(time epochtime.EpochTime, factor *quantity.Quantity, accounts []signature.PublicKey) error {\n\tsteps, err := s.RewardSchedule()\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar activeStep *staking.RewardStep\n\tfor _, step := range steps {\n\t\tif time < step.Until {\n\t\t\tactiveStep = &step\n\t\t\tbreak\n\t\t}\n\t}\n\tif activeStep == nil {\n\t\t// We're past the end of the schedule.\n\t\treturn nil\n\t}\n\n\tcommonPool, err := s.CommonPool()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"loading common pool\")\n\t}\n\n\tfor _, id := range accounts {\n\t\tent := s.Account(id)\n\n\t\tq := ent.Escrow.Active.Balance.Clone()\n\t\t// Multiply first.\n\t\tif err := q.Mul(factor); err != nil {\n\t\t\treturn errors.Wrap(err, \"multiplying by reward factor\")\n\t\t}\n\t\tif err := q.Mul(&activeStep.Scale); err != nil {\n\t\t\treturn errors.Wrap(err, \"multiplying by reward step scale\")\n\t\t}\n\t\tif err := q.Quo(staking.RewardAmountDenominator); err != nil {\n\t\t\treturn errors.Wrap(err, \"dividing by reward amount denominator\")\n\t\t}\n\n\t\tif q.IsZero() {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar com *quantity.Quantity\n\t\trate := ent.Escrow.CommissionSchedule.CurrentRate(time)\n\t\tif rate != nil {\n\t\t\tcom = q.Clone()\n\t\t\t// Multiply first.\n\t\t\tif err := com.Mul(rate); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"multiplying by commission rate\")\n\t\t\t}\n\t\t\tif err := com.Quo(staking.CommissionRateDenominator); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"dividing by commission rate denominator\")\n\t\t\t}\n\n\t\t\tif err := q.Sub(com); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"subtracting commission\")\n\t\t\t}\n\t\t}\n\n\t\tif !q.IsZero() {\n\t\t\tif err := quantity.Move(&ent.Escrow.Active.Balance, commonPool, q); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"transferring to active escrow balance from common pool\")\n\t\t\t}\n\t\t}\n\n\t\tif com != nil && !com.IsZero() {\n\t\t\tdelegation := s.Delegation(id, id)\n\n\t\t\tif err := ent.Escrow.Active.Deposit(&delegation.Shares, commonPool, com); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"depositing commission\")\n\t\t\t}\n\n\t\t\ts.SetDelegation(id, id, delegation)\n\t\t}\n\n\t\ts.SetAccount(id, ent)\n\t}\n\n\ts.SetCommonPool(commonPool)\n\n\treturn nil\n}", "func (k Keeper) ClaimDelegatorReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tclaim, found := k.GetDelegatorClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tsyncedClaim, err := k.SynchronizeDelegatorClaim(ctx, claim)\n\tif err != nil {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr = k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetDelegatorClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func ApplyRewardTx(tx *types.Transaction, statedb *state.Statedb) (*types.Receipt, error) {\n\tstatedb.CreateAccount(tx.Data.To)\n\tstatedb.AddBalance(tx.Data.To, tx.Data.Amount)\n\n\thash, err := statedb.Hash()\n\tif err != nil {\n\t\treturn nil, errors.NewStackedError(err, \"failed to get statedb root hash\")\n\t}\n\n\treceipt := &types.Receipt{\n\t\tTxHash: tx.Hash,\n\t\tPostState: hash,\n\t}\n\n\treturn receipt, nil\n}", "func (n Network) ChainReward(ctx context.Context, launchID uint64) (rewardtypes.RewardPool, error) {\n\tres, err := n.rewardQuery.\n\t\tRewardPool(ctx,\n\t\t\t&rewardtypes.QueryGetRewardPoolRequest{\n\t\t\t\tLaunchID: launchID,\n\t\t\t},\n\t\t)\n\n\tif cosmoserror.Unwrap(err) == cosmoserror.ErrNotFound {\n\t\treturn rewardtypes.RewardPool{}, ErrObjectNotFound\n\t} else if err != nil {\n\t\treturn rewardtypes.RewardPool{}, err\n\t}\n\treturn res.RewardPool, nil\n}", "func (va ClawbackVestingAccount) postReward(ctx sdk.Context, reward sdk.Coins, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) {\n\t// Find the scheduled amount of vested and unvested staking tokens\n\tbondDenom := sk.BondDenom(ctx)\n\tvested := ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, ctx.BlockTime().Unix()).AmountOf(bondDenom)\n\tunvested := va.OriginalVesting.AmountOf(bondDenom).Sub(vested)\n\n\tif unvested.IsZero() {\n\t\t// no need to adjust the vesting schedule\n\t\treturn\n\t}\n\n\tif vested.IsZero() {\n\t\t// all staked tokens must be unvested\n\t\tva.distributeReward(ctx, ak, bondDenom, reward)\n\t\treturn\n\t}\n\n\t// Find current split of account balance on staking axis\n\tbonded := sk.GetDelegatorBonded(ctx, va.GetAddress())\n\tunbonding := sk.GetDelegatorUnbonding(ctx, va.GetAddress())\n\tdelegated := bonded.Add(unbonding)\n\n\t// discover what has been slashed and remove from delegated amount\n\toldDelegated := va.DelegatedVesting.AmountOf(bondDenom).Add(va.DelegatedFree.AmountOf(bondDenom))\n\tslashed := oldDelegated.Sub(intMin(oldDelegated, delegated))\n\tdelegated = delegated.Sub(intMin(delegated, slashed))\n\n\t// Prefer delegated tokens to be unvested\n\tunvested = intMin(unvested, delegated)\n\tvested = delegated.Sub(unvested)\n\n\t// Compute the unvested amount of reward and add to vesting schedule\n\tif unvested.IsZero() {\n\t\treturn\n\t}\n\tif vested.IsZero() {\n\t\tva.distributeReward(ctx, ak, bondDenom, reward)\n\t\treturn\n\t}\n\tunvestedRatio := unvested.ToDec().QuoTruncate(bonded.ToDec()) // round down\n\tunvestedReward := scaleCoins(reward, unvestedRatio)\n\tva.distributeReward(ctx, ak, bondDenom, unvestedReward)\n}", "func (_Smartchef *SmartchefCallerSession) PendingReward(_user common.Address) (*big.Int, error) {\n\treturn _Smartchef.Contract.PendingReward(&_Smartchef.CallOpts, _user)\n}", "func (_IStakingRewards *IStakingRewardsSession) GetReward() (*types.Transaction, error) {\n\treturn _IStakingRewards.Contract.GetReward(&_IStakingRewards.TransactOpts)\n}", "func (_Smartchef *SmartchefTransactorSession) StopReward() (*types.Transaction, error) {\n\treturn _Smartchef.Contract.StopReward(&_Smartchef.TransactOpts)\n}", "func (me TGetReviewableHITsSortProperty) IsReward() bool { return me.String() == \"Reward\" }", "func (m *MemoryRewardStorage) Update(reward rewards.Reward) {\n\tfor index, r := range m.rewards {\n\t\tif r.ID == reward.ID {\n\t\t\tm.rewards[index] = reward\n\t\t}\n\t}\n}", "func (_RewardsDistributionRecipient *RewardsDistributionRecipientTransactorSession) NotifyRewardAmount(reward *big.Int) (*types.Transaction, error) {\n\treturn _RewardsDistributionRecipient.Contract.NotifyRewardAmount(&_RewardsDistributionRecipient.TransactOpts, reward)\n}", "func (_Token *TokenCallerSession) CurrentReward(account common.Address) (struct {\n\tInitialDeposit *big.Int\n\tReward *big.Int\n}, error) {\n\treturn _Token.Contract.CurrentReward(&_Token.CallOpts, account)\n}", "func (_TrialRulesAbstract *TrialRulesAbstractCaller) GetReward(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _TrialRulesAbstract.contract.Call(opts, out, \"getReward\")\n\treturn *ret0, err\n}", "func (del Delegation) ClaimedReward() (hexutil.Big, error) {\n\tval, err := repository.R().RewardsClaimed(&del.Address, (*big.Int)(del.Delegation.ToStakerId), nil, nil)\n\tif err != nil {\n\t\treturn hexutil.Big{}, err\n\t}\n\treturn (hexutil.Big)(*val), nil\n}", "func (_RewardsDistributionRecipient *RewardsDistributionRecipientSession) NotifyRewardAmount(reward *big.Int) (*types.Transaction, error) {\n\treturn _RewardsDistributionRecipient.Contract.NotifyRewardAmount(&_RewardsDistributionRecipient.TransactOpts, reward)\n}", "func (_Contract *ContractCaller) TaskErasingReward(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Contract.contract.Call(opts, &out, \"taskErasingReward\")\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 (k Keeper) GetReward(ctx sdk.Context, stakingCoinDenom string, farmerAcc sdk.AccAddress) (reward types.Reward, found bool) {\n\tstore := ctx.KVStore(k.storeKey)\n\tbz := store.Get(types.GetRewardKey(stakingCoinDenom, farmerAcc))\n\tif bz == nil {\n\t\treturn reward, false\n\t}\n\tvar rewardCoins types.RewardCoins\n\tk.cdc.MustUnmarshal(bz, &rewardCoins)\n\treturn types.Reward{\n\t\tFarmer: farmerAcc.String(),\n\t\tStakingCoinDenom: stakingCoinDenom,\n\t\tRewardCoins: rewardCoins.RewardCoins,\n\t}, true\n}", "func (_Dospayment *DospaymentTransactor) ClaimGuardianReward(opts *bind.TransactOpts, guardianAddr common.Address) (*types.Transaction, error) {\n\treturn _Dospayment.contract.Transact(opts, \"claimGuardianReward\", guardianAddr)\n}", "func (_Smartchef *SmartchefSession) PendingReward(_user common.Address) (*big.Int, error) {\n\treturn _Smartchef.Contract.PendingReward(&_Smartchef.CallOpts, _user)\n}", "func (_Smartchef *SmartchefSession) StopReward() (*types.Transaction, error) {\n\treturn _Smartchef.Contract.StopReward(&_Smartchef.TransactOpts)\n}", "func (_TrialRulesAbstract *TrialRulesAbstractCallerSession) GetReward() (*big.Int, error) {\n\treturn _TrialRulesAbstract.Contract.GetReward(&_TrialRulesAbstract.CallOpts)\n}", "func (_Contract *ContractCallerSession) TaskHandlingReward() (*big.Int, error) {\n\treturn _Contract.Contract.TaskHandlingReward(&_Contract.CallOpts)\n}", "func (q querier) RewardWeight(c context.Context, req *types.QueryRewardWeightRequest) (*types.QueryRewardWeightResponse, error) {\n\tctx := sdk.UnwrapSDKContext(c)\n\treturn &types.QueryRewardWeightResponse{RewardWeight: q.GetRewardWeight(ctx)}, nil\n}", "func (_Token *TokenSession) CurrentReward(account common.Address) (struct {\n\tInitialDeposit *big.Int\n\tReward *big.Int\n}, error) {\n\treturn _Token.Contract.CurrentReward(&_Token.CallOpts, account)\n}", "func (c *Calculator) votingReward(\n\tmultiplier *big.Int,\n\tdivider *big.Int,\n\tfrom int,\n\tto int,\n\tprepInfo map[string]*pRepEnable,\n\titer icstate.VotingIterator,\n) *big.Int {\n\ttotal := new(big.Int)\n\tcheckMinVoting := c.global.GetIISSVersion() == icstate.IISSVersion2\n\tfor ; iter.Has(); iter.Next() {\n\t\tif voting, err := iter.Get(); err != nil {\n\t\t\tc.log.Errorf(\"Failed to iterate votings err=%+v\", err)\n\t\t} else {\n\t\t\tif checkMinVoting && voting.Amount().Cmp(BigIntMinDelegation) < 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ts := from\n\t\t\te := to\n\t\t\tif prep, ok := prepInfo[icutils.ToKey(voting.To())]; ok {\n\t\t\t\tif prep.StartOffset() != 0 && prep.StartOffset() > s {\n\t\t\t\t\ts = prep.StartOffset()\n\t\t\t\t}\n\t\t\t\tif prep.EndOffset() != 0 && prep.EndOffset() < e {\n\t\t\t\t\te = prep.EndOffset()\n\t\t\t\t}\n\t\t\t\tperiod := e - s\n\t\t\t\tif period <= 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\treward := new(big.Int).Mul(multiplier, voting.Amount())\n\t\t\t\treward.Mul(reward, big.NewInt(int64(period)))\n\t\t\t\treward.Div(reward, divider)\n\t\t\t\ttotal.Add(total, reward)\n\t\t\t\tc.log.Tracef(\"VotingReward %s: %s = %s * %s * %d / %s\",\n\t\t\t\t\tvoting.To(), reward, multiplier, voting.Amount(), period, divider)\n\t\t\t}\n\t\t}\n\t}\n\treturn total\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactorSession) DistributeETHReward() (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.DistributeETHReward(&_BondedECDSAKeep.TransactOpts)\n}", "func (_Lmc *LmcCaller) RewardPerBlock(opts *bind.CallOpts, arg0 *big.Int) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Lmc.contract.Call(opts, &out, \"rewardPerBlock\", arg0)\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 (me *XsdGoPkgHasElem_RewardsequenceCreateHITRequestschema_Reward_TPrice_) Walk() (err error) {\n\tif fn := WalkHandlers.XsdGoPkgHasElem_RewardsequenceCreateHITRequestschema_Reward_TPrice_; 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 err = me.Reward.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\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 (_XStaking *XStakingFilterer) ParseRewardPaid(log types.Log) (*XStakingRewardPaid, error) {\n\tevent := new(XStakingRewardPaid)\n\tif err := _XStaking.contract.UnpackLog(event, \"RewardPaid\", log); err != nil {\n\t\treturn nil, err\n\t}\n\treturn event, nil\n}", "func (_XStaking *XStakingTransactorSession) GetReward() (*types.Transaction, error) {\n\treturn _XStaking.Contract.GetReward(&_XStaking.TransactOpts)\n}", "func MeanReward(r []*Rollout) float64 {\n\tvar sum float64\n\tfor _, x := range r {\n\t\tsum += x.Reward\n\t}\n\treturn sum / float64(len(r))\n}", "func (p *Protocol) updateRewardHistory(tx *sql.Tx, epochNumber uint64, actionHash string, rewardInfoMap map[string]*RewardInfo) error {\n\tvalStrs := make([]string, 0, len(rewardInfoMap))\n\tvalArgs := make([]interface{}, 0, len(rewardInfoMap)*7)\n\tfor rewardAddress, rewards := range rewardInfoMap {\n\t\tblockReward := rewards.BlockReward.String()\n\t\tepochReward := rewards.EpochReward.String()\n\t\tfoundationBonus := rewards.FoundationBonus.String()\n\n\t\tvar candidateName string\n\t\t// If more than one candidates share the same reward address, just use the first candidate as their delegate\n\t\tif len(p.RewardAddrToName[rewardAddress]) > 0 {\n\t\t\tcandidateName = p.RewardAddrToName[rewardAddress][0]\n\t\t}\n\n\t\tvalStrs = append(valStrs, \"(?, ?, ?, ?, CAST(? as DECIMAL(65, 0)), CAST(? as DECIMAL(65, 0)), CAST(? as DECIMAL(65, 0)))\")\n\t\tvalArgs = append(valArgs, epochNumber, actionHash, rewardAddress, candidateName, blockReward, epochReward, foundationBonus)\n\t}\n\tinsertQuery := fmt.Sprintf(insertRewardHistory, RewardHistoryTableName, strings.Join(valStrs, \",\"))\n\n\tif _, err := tx.Exec(insertQuery, valArgs...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (_XStaking *XStakingCaller) RewardRate(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _XStaking.contract.Call(opts, &out, \"rewardRate\")\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 (_XStaking *XStakingFilterer) WatchRewardPaid(opts *bind.WatchOpts, sink chan<- *XStakingRewardPaid, user []common.Address) (event.Subscription, error) {\n\n\tvar userRule []interface{}\n\tfor _, userItem := range user {\n\t\tuserRule = append(userRule, userItem)\n\t}\n\n\tlogs, sub, err := _XStaking.contract.WatchLogs(opts, \"RewardPaid\", userRule)\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(XStakingRewardPaid)\n\t\t\t\tif err := _XStaking.contract.UnpackLog(event, \"RewardPaid\", 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 (_XStaking *XStakingSession) GetReward() (*types.Transaction, error) {\n\treturn _XStaking.Contract.GetReward(&_XStaking.TransactOpts)\n}", "func (d *Dao) HasReward(c context.Context, uid int64) (r int64, err error) {\n\trst, err := d.GetHasReward(c, uid)\n\tif err != nil {\n\t\tif err == memcache.ErrNotFound {\n\t\t\treward, err2 := d.findByUid(uid, true)\n\t\t\tif err2 != nil {\n\t\t\t\treturn rst, err2\n\t\t\t}\n\t\t\tif reward != nil {\n\t\t\t\trst = int64(1)\n\t\t\t\td.SetHasReward(c, uid, rst)\n\t\t\t} else {\n\t\t\t\trst = int64(0)\n\t\t\t\td.SetHasReward(c, uid, rst)\n\t\t\t}\n\t\t\treturn rst, err\n\t\t}\n\t\tlog.Error(\"HasReward(%v) error(%v)\", uid, err)\n\t\treturn rst, err\n\t}\n\treturn rst, err\n}", "func (_XStaking *XStakingCallerSession) UserRewardPerTokenPaid(arg0 common.Address) (*big.Int, error) {\n\treturn _XStaking.Contract.UserRewardPerTokenPaid(&_XStaking.CallOpts, arg0)\n}", "func (_BondedECDSAKeep *BondedECDSAKeepSession) DistributeETHReward() (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.DistributeETHReward(&_BondedECDSAKeep.TransactOpts)\n}", "func (_XStaking *XStakingCallerSession) Rewards(arg0 common.Address) (*big.Int, error) {\n\treturn _XStaking.Contract.Rewards(&_XStaking.CallOpts, arg0)\n}", "func (httpServer *HttpServer) handleListRewardAmount(params interface{}, closeChan <-chan struct{}) (interface{}, *rpcservice.RPCError) {\n\tresult := httpServer.databaseService.ListRewardAmount()\n\treturn result, nil\n}", "func (as AccountStorage) GetReward(ctx sdk.Context, accKey types.AccountKey) (*Reward, sdk.Error) {\n\tstore := ctx.KVStore(as.key)\n\trewardByte := store.Get(getRewardKey(accKey))\n\tif rewardByte == nil {\n\t\treturn nil, ErrRewardNotFound()\n\t}\n\treward := new(Reward)\n\tif err := as.cdc.UnmarshalJSON(rewardByte, reward); err != nil {\n\t\treturn nil, ErrFailedToUnmarshalReward(err)\n\t}\n\treturn reward, nil\n}", "func (_Lmc *LmcCallerSession) GetUserRewardDebt(_userAddress common.Address, _index *big.Int) (*big.Int, error) {\n\treturn _Lmc.Contract.GetUserRewardDebt(&_Lmc.CallOpts, _userAddress, _index)\n}", "func (m *DestinyDefinitionsMilestonesDestinyMilestoneQuestRewardItem) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (_Lmc *LmcCallerSession) RewardPerBlock(arg0 *big.Int) (*big.Int, error) {\n\treturn _Lmc.Contract.RewardPerBlock(&_Lmc.CallOpts, arg0)\n}", "func (_XStaking *XStakingSession) Rewards(arg0 common.Address) (*big.Int, error) {\n\treturn _XStaking.Contract.Rewards(&_XStaking.CallOpts, arg0)\n}", "func (me TSearchHITsSortProperty) IsReward() bool { return me.String() == \"Reward\" }", "func (_Lmc *LmcSession) RewardPerBlock(arg0 *big.Int) (*big.Int, error) {\n\treturn _Lmc.Contract.RewardPerBlock(&_Lmc.CallOpts, arg0)\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactorSession) DistributeERC20Reward(_tokenAddress common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.DistributeERC20Reward(&_BondedECDSAKeep.TransactOpts, _tokenAddress, _value)\n}", "func (_TrialRulesAbstract *TrialRulesAbstractSession) GetReward() (*big.Int, error) {\n\treturn _TrialRulesAbstract.Contract.GetReward(&_TrialRulesAbstract.CallOpts)\n}", "func (_XStaking *XStakingFilterer) WatchRewardAdded(opts *bind.WatchOpts, sink chan<- *XStakingRewardAdded) (event.Subscription, error) {\n\n\tlogs, sub, err := _XStaking.contract.WatchLogs(opts, \"RewardAdded\")\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(XStakingRewardAdded)\n\t\t\t\tif err := _XStaking.contract.UnpackLog(event, \"RewardAdded\", 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 (_Contract *ContractSession) TaskHandlingReward() (*big.Int, error) {\n\treturn _Contract.Contract.TaskHandlingReward(&_Contract.CallOpts)\n}", "func (_RewardsDistributionRecipient *RewardsDistributionRecipientTransactor) NotifyRewardAmount(opts *bind.TransactOpts, reward *big.Int) (*types.Transaction, error) {\n\treturn _RewardsDistributionRecipient.contract.Transact(opts, \"notifyRewardAmount\", reward)\n}", "func (msg MsgClaimUSDXMintingReward) Type() string { return TypeMsgClaimUSDXMintingReward }", "func (r *Rewarding) BlockReward() *big.Int {\n\tval, ok := new(big.Int).SetString(r.BlockRewardStr, 10)\n\tif !ok {\n\t\tlog.S().Panicf(\"Error when casting block reward string %s into big int\", r.BlockRewardStr)\n\t}\n\treturn val\n}", "func (_Lmc *LmcSession) GetUserRewardDebt(_userAddress common.Address, _index *big.Int) (*big.Int, error) {\n\treturn _Lmc.Contract.GetUserRewardDebt(&_Lmc.CallOpts, _userAddress, _index)\n}", "func (_XStaking *XStakingSession) UserRewardPerTokenPaid(arg0 common.Address) (*big.Int, error) {\n\treturn _XStaking.Contract.UserRewardPerTokenPaid(&_XStaking.CallOpts, arg0)\n}" ]
[ "0.6228627", "0.6163718", "0.60478336", "0.603172", "0.6024607", "0.5981112", "0.5969014", "0.59682953", "0.59496", "0.59159184", "0.5895051", "0.5894164", "0.5851955", "0.5822973", "0.57389563", "0.56443095", "0.5625199", "0.5603768", "0.5591688", "0.55578643", "0.5497458", "0.54913", "0.5485651", "0.54785264", "0.5459176", "0.5456478", "0.5455661", "0.5433399", "0.5428552", "0.5421066", "0.5400683", "0.53939676", "0.53790295", "0.5357424", "0.53563786", "0.53321487", "0.5329579", "0.52970684", "0.5296688", "0.5289166", "0.5286446", "0.5265115", "0.52425015", "0.52381027", "0.52209747", "0.5220343", "0.5220156", "0.52146167", "0.5206164", "0.5193927", "0.51557475", "0.5139185", "0.51309204", "0.5128314", "0.51251996", "0.5115334", "0.51144314", "0.51130533", "0.5105608", "0.50974107", "0.50949985", "0.509375", "0.50915396", "0.5073", "0.50704926", "0.5068857", "0.50632036", "0.5058857", "0.5056796", "0.50554484", "0.5054147", "0.5047337", "0.50439477", "0.5022599", "0.5020046", "0.4997247", "0.4988397", "0.49864525", "0.49767706", "0.49717173", "0.4961796", "0.4961348", "0.49515942", "0.49492058", "0.49430174", "0.49401253", "0.49275827", "0.49239883", "0.49234566", "0.491311", "0.49102077", "0.49084952", "0.490803", "0.49062353", "0.4902244", "0.489186", "0.4877863", "0.48679137", "0.48677853", "0.48640245" ]
0.78040135
0
PostReward implements the exported.ClawbackVestingAccountI interface.
PostReward реализует интерфейс exported.ClawbackVestingAccountI.
func (va *ClawbackVestingAccount) PostReward(ctx sdk.Context, reward sdk.Coins, action exported.RewardAction) error { return action.ProcessReward(ctx, reward, va) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (va ClawbackVestingAccount) postReward(ctx sdk.Context, reward sdk.Coins, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) {\n\t// Find the scheduled amount of vested and unvested staking tokens\n\tbondDenom := sk.BondDenom(ctx)\n\tvested := ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, ctx.BlockTime().Unix()).AmountOf(bondDenom)\n\tunvested := va.OriginalVesting.AmountOf(bondDenom).Sub(vested)\n\n\tif unvested.IsZero() {\n\t\t// no need to adjust the vesting schedule\n\t\treturn\n\t}\n\n\tif vested.IsZero() {\n\t\t// all staked tokens must be unvested\n\t\tva.distributeReward(ctx, ak, bondDenom, reward)\n\t\treturn\n\t}\n\n\t// Find current split of account balance on staking axis\n\tbonded := sk.GetDelegatorBonded(ctx, va.GetAddress())\n\tunbonding := sk.GetDelegatorUnbonding(ctx, va.GetAddress())\n\tdelegated := bonded.Add(unbonding)\n\n\t// discover what has been slashed and remove from delegated amount\n\toldDelegated := va.DelegatedVesting.AmountOf(bondDenom).Add(va.DelegatedFree.AmountOf(bondDenom))\n\tslashed := oldDelegated.Sub(intMin(oldDelegated, delegated))\n\tdelegated = delegated.Sub(intMin(delegated, slashed))\n\n\t// Prefer delegated tokens to be unvested\n\tunvested = intMin(unvested, delegated)\n\tvested = delegated.Sub(unvested)\n\n\t// Compute the unvested amount of reward and add to vesting schedule\n\tif unvested.IsZero() {\n\t\treturn\n\t}\n\tif vested.IsZero() {\n\t\tva.distributeReward(ctx, ak, bondDenom, reward)\n\t\treturn\n\t}\n\tunvestedRatio := unvested.ToDec().QuoTruncate(bonded.ToDec()) // round down\n\tunvestedReward := scaleCoins(reward, unvestedRatio)\n\tva.distributeReward(ctx, ak, bondDenom, unvestedReward)\n}", "func (cra clawbackRewardAction) ProcessReward(ctx sdk.Context, reward sdk.Coins, rawAccount exported.VestingAccount) error {\n\tcva, ok := rawAccount.(*ClawbackVestingAccount)\n\tif !ok {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrNotSupported, \"expected *ClawbackVestingAccount, got %T\", rawAccount)\n\t}\n\tcva.postReward(ctx, reward, cra.ak, cra.bk, cra.sk)\n\treturn nil\n}", "func (va ClawbackVestingAccount) distributeReward(ctx sdk.Context, ak AccountKeeper, bondDenom string, reward sdk.Coins) {\n\tnow := ctx.BlockTime().Unix()\n\tt := va.StartTime\n\tfirstUnvestedPeriod := 0\n\tunvestedTokens := sdk.ZeroInt()\n\tfor i, period := range va.VestingPeriods {\n\t\tt += period.Length\n\t\tif t <= now {\n\t\t\tfirstUnvestedPeriod = i + 1\n\t\t\tcontinue\n\t\t}\n\t\tunvestedTokens = unvestedTokens.Add(period.Amount.AmountOf(bondDenom))\n\t}\n\n\trunningTotReward := sdk.NewCoins()\n\trunningTotStaking := sdk.ZeroInt()\n\tfor i := firstUnvestedPeriod; i < len(va.VestingPeriods); i++ {\n\t\tperiod := va.VestingPeriods[i]\n\t\trunningTotStaking = runningTotStaking.Add(period.Amount.AmountOf(bondDenom))\n\t\trunningTotRatio := runningTotStaking.ToDec().Quo(unvestedTokens.ToDec())\n\t\ttargetCoins := scaleCoins(reward, runningTotRatio)\n\t\tthisReward := targetCoins.Sub(runningTotReward)\n\t\trunningTotReward = targetCoins\n\t\tperiod.Amount = period.Amount.Add(thisReward...)\n\t\tva.VestingPeriods[i] = period\n\t}\n\n\tva.OriginalVesting = va.OriginalVesting.Add(reward...)\n\tak.SetAccount(ctx, &va)\n}", "func (a Actor) AwardBlockReward(rt vmr.Runtime, params *AwardBlockRewardParams) *adt.EmptyValue {\n\trt.ValidateImmediateCallerIs(builtin.SystemActorAddr)\n\tAssertMsg(rt.CurrentBalance().GreaterThanEqual(params.GasReward),\n\t\t\"actor current balance %v insufficient to pay gas reward %v\", rt.CurrentBalance(), params.GasReward)\n\n\tAssertMsg(params.TicketCount > 0, \"cannot give block reward for zero tickets\")\n\n\tminer, ok := rt.ResolveAddress(params.Miner)\n\tif !ok {\n\t\trt.Abortf(exitcode.ErrIllegalState, \"failed to resolve given owner address\")\n\t}\n\n\tpriorBalance := rt.CurrentBalance()\n\n\tvar penalty abi.TokenAmount\n\tvar st State\n\trt.State().Transaction(&st, func() interface{} {\n\t\tblockReward := a.computeBlockReward(&st, big.Sub(priorBalance, params.GasReward), params.TicketCount)\n\t\ttotalReward := big.Add(blockReward, params.GasReward)\n\n\t\t// Cap the penalty at the total reward value.\n\t\tpenalty = big.Min(params.Penalty, totalReward)\n\n\t\t// Reduce the payable reward by the penalty.\n\t\trewardPayable := big.Sub(totalReward, penalty)\n\n\t\tAssertMsg(big.Add(rewardPayable, penalty).LessThanEqual(priorBalance),\n\t\t\t\"reward payable %v + penalty %v exceeds balance %v\", rewardPayable, penalty, priorBalance)\n\n\t\t// Record new reward into reward map.\n\t\tif rewardPayable.GreaterThan(abi.NewTokenAmount(0)) {\n\t\t\tnewReward := Reward{\n\t\t\t\tStartEpoch: rt.CurrEpoch(),\n\t\t\t\tEndEpoch: rt.CurrEpoch() + rewardVestingPeriod,\n\t\t\t\tValue: rewardPayable,\n\t\t\t\tAmountWithdrawn: abi.NewTokenAmount(0),\n\t\t\t\tVestingFunction: rewardVestingFunction,\n\t\t\t}\n\t\t\tif err := st.addReward(adt.AsStore(rt), miner, &newReward); err != nil {\n\t\t\t\trt.Abortf(exitcode.ErrIllegalState, \"failed to add reward to rewards map: %w\", err)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\n\t// Burn the penalty amount.\n\t_, code := rt.Send(builtin.BurntFundsActorAddr, builtin.MethodSend, nil, penalty)\n\tbuiltin.RequireSuccess(rt, code, \"failed to send penalty to BurntFundsActor\")\n\n\treturn nil\n}", "func (c *Coinbase) AddReward(output *Output) {\n\toutput.EncryptedMask = make([]byte, 1)\n\tc.Rewards = append(c.Rewards, output)\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 (_Token *TokenCaller) BaseReward(opts *bind.CallOpts, index *big.Int) (*big.Int, *big.Int, *big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t\tret1 = new(*big.Int)\n\t\tret2 = new(*big.Int)\n\t)\n\tout := &[]interface{}{\n\t\tret0,\n\t\tret1,\n\t\tret2,\n\t}\n\terr := _Token.contract.Call(opts, out, \"baseReward\", index)\n\treturn *ret0, *ret1, *ret2, err\n}", "func (_Token *TokenCallerSession) BaseReward(index *big.Int) (*big.Int, *big.Int, *big.Int, error) {\n\treturn _Token.Contract.BaseReward(&_Token.CallOpts, index)\n}", "func (_Token *TokenSession) BaseReward(index *big.Int) (*big.Int, *big.Int, *big.Int, error) {\n\treturn _Token.Contract.BaseReward(&_Token.CallOpts, index)\n}", "func (d *Dao) AddReward(c context.Context, iRewardID int64, uid int64, iSource int64, iRoomid int64, iLifespan int64) (err error) {\n\t//aReward, _ := getRewardConfByLid(iRewardID)\n\n\tm, _ := time.ParseDuration(fmt.Sprintf(\"+%dh\", iLifespan))\n\n\targ := &AnchorTaskModel.AnchorReward{\n\t\tUid: uid,\n\t\tRewardId: iRewardID,\n\t\tRoomid: iRoomid,\n\t\tSource: iSource,\n\t\tAchieveTime: xtime.Time(time.Now().Unix()),\n\t\tExpireTime: xtime.Time(time.Now().Add(m).Unix()),\n\t\tStatus: model.RewardUnUsed,\n\t}\n\n\t//spew.Dump\n\t// (arg)\n\tif err := d.orm.Create(arg).Error; err != nil {\n\t\tlog.Error(\"addReward(%v) error(%v)\", arg, err)\n\t\treturn err\n\t}\n\n\tif err := d.SetNewReward(c, uid, int64(1)); err != nil {\n\t\tlog.Error(\"addRewardMc(%v) error(%v)\", uid, err)\n\t}\n\n\tif err := d.SetHasReward(c, uid, int64(1)); err != nil {\n\t\tlog.Error(\"SetHasReward(%v) error(%v)\", uid, err)\n\t}\n\n\tlog.Info(\"addReward (%v) succ\", arg)\n\n\treturn\n}", "func (as AccountStorage) SetReward(ctx sdk.Context, accKey types.AccountKey, reward *Reward) sdk.Error {\n\tstore := ctx.KVStore(as.key)\n\trewardByte, err := as.cdc.MarshalJSON(*reward)\n\tif err != nil {\n\t\treturn ErrFailedToMarshalReward(err)\n\t}\n\tstore.Set(getRewardKey(accKey), rewardByte)\n\treturn nil\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactor) DistributeETHReward(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.contract.Transact(opts, \"distributeETHReward\")\n}", "func (_Smartchef *SmartchefTransactor) StopReward(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _Smartchef.contract.Transact(opts, \"stopReward\")\n}", "func (c *Client) RenterPostAllowance(allowance modules.Allowance) (err error) {\n\tvalues := url.Values{}\n\tvalues.Set(\"funds\", allowance.Funds.String())\n\tvalues.Set(\"hosts\", strconv.FormatUint(allowance.Hosts, 10))\n\tvalues.Set(\"period\", strconv.FormatUint(uint64(allowance.Period), 10))\n\tvalues.Set(\"renewwindow\", strconv.FormatUint(uint64(allowance.RenewWindow), 10))\n\terr = c.post(\"/renter\", values.Encode(), nil)\n\treturn\n}", "func EstimateReward(reward, pr, gamma float64) float64 {\n\tret := reward / (pr + gamma)\n\tlog.Logf(MABLogLevel, \"MAB Estimate Reward: %v / (%v + %v) = %v\\n\",\n\t\treward, pr, gamma, ret)\n\treturn ret\n}", "func (_Dospayment *DospaymentTransactor) ClaimGuardianReward(opts *bind.TransactOpts, guardianAddr common.Address) (*types.Transaction, error) {\n\treturn _Dospayment.contract.Transact(opts, \"claimGuardianReward\", guardianAddr)\n}", "func ViewReward(rw http.ResponseWriter, r *http.Request) {\n\t// get the token\n\treqToken := r.Header.Get(\"Authorization\")\n\t\n\t// get the claims\n\tclaims, isNotValid := GetClaims(reqToken, rw)\n\tif isNotValid {\n\t\treturn\n\t}\n\n\tdt, err := db.GetUserRewards(claims.Roll)\n\tif err != nil {\n\t\trw.WriteHeader(http.StatusInternalServerError)\n\t\trw.Write(Rsp(err.Error(), \"Server Error\"))\n\t\treturn\n\t}\n\trw.WriteHeader(http.StatusOK)\n\tres := c.RespData{\n\t\tMessage: \"All data\",\n\t\tData: dt,\n\t}\n\tjson.NewEncoder(rw).Encode(res)\n}", "func (s *MutableState) AddRewards(time epochtime.EpochTime, factor *quantity.Quantity, accounts []signature.PublicKey) error {\n\tsteps, err := s.RewardSchedule()\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar activeStep *staking.RewardStep\n\tfor _, step := range steps {\n\t\tif time < step.Until {\n\t\t\tactiveStep = &step\n\t\t\tbreak\n\t\t}\n\t}\n\tif activeStep == nil {\n\t\t// We're past the end of the schedule.\n\t\treturn nil\n\t}\n\n\tcommonPool, err := s.CommonPool()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"loading common pool\")\n\t}\n\n\tfor _, id := range accounts {\n\t\tent := s.Account(id)\n\n\t\tq := ent.Escrow.Active.Balance.Clone()\n\t\t// Multiply first.\n\t\tif err := q.Mul(factor); err != nil {\n\t\t\treturn errors.Wrap(err, \"multiplying by reward factor\")\n\t\t}\n\t\tif err := q.Mul(&activeStep.Scale); err != nil {\n\t\t\treturn errors.Wrap(err, \"multiplying by reward step scale\")\n\t\t}\n\t\tif err := q.Quo(staking.RewardAmountDenominator); err != nil {\n\t\t\treturn errors.Wrap(err, \"dividing by reward amount denominator\")\n\t\t}\n\n\t\tif q.IsZero() {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar com *quantity.Quantity\n\t\trate := ent.Escrow.CommissionSchedule.CurrentRate(time)\n\t\tif rate != nil {\n\t\t\tcom = q.Clone()\n\t\t\t// Multiply first.\n\t\t\tif err := com.Mul(rate); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"multiplying by commission rate\")\n\t\t\t}\n\t\t\tif err := com.Quo(staking.CommissionRateDenominator); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"dividing by commission rate denominator\")\n\t\t\t}\n\n\t\t\tif err := q.Sub(com); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"subtracting commission\")\n\t\t\t}\n\t\t}\n\n\t\tif !q.IsZero() {\n\t\t\tif err := quantity.Move(&ent.Escrow.Active.Balance, commonPool, q); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"transferring to active escrow balance from common pool\")\n\t\t\t}\n\t\t}\n\n\t\tif com != nil && !com.IsZero() {\n\t\t\tdelegation := s.Delegation(id, id)\n\n\t\t\tif err := ent.Escrow.Active.Deposit(&delegation.Shares, commonPool, com); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"depositing commission\")\n\t\t\t}\n\n\t\t\ts.SetDelegation(id, id, delegation)\n\t\t}\n\n\t\ts.SetAccount(id, ent)\n\t}\n\n\ts.SetCommonPool(commonPool)\n\n\treturn nil\n}", "func (node *TreeNode) backpropagateReward(scores [2]float64) {\n\tcurrentNode := node\n\tfor currentNode.Parent != nil {\n\t\tcurrentNode.VisitCount += 1.0\n\t\tcurrentNode.CumulativeScore[0] += scores[0]\n\t\tcurrentNode.CumulativeScore[1] += scores[1]\n\t\tcurrentNode = currentNode.Parent\n\t}\n\t//Increment root node counter\n\tcurrentNode.VisitCount += 1.0\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactorSession) DistributeETHReward() (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.DistributeETHReward(&_BondedECDSAKeep.TransactOpts)\n}", "func (k Keeper) ClaimSwapReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tsyncedClaim, found := k.GetSynchronizedSwapClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr := k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetSwapClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func (k Keeper) ClaimEarnReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tsyncedClaim, found := k.GetSynchronizedEarnClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr := k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetEarnClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func (_BondedECDSAKeep *BondedECDSAKeepSession) DistributeETHReward() (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.DistributeETHReward(&_BondedECDSAKeep.TransactOpts)\n}", "func (client CloudEndpointsClient) PostBackupResponder(resp *http.Response) (result PostBackupResponse, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (_Smartchef *SmartchefCaller) PendingReward(opts *bind.CallOpts, _user common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Smartchef.contract.Call(opts, out, \"pendingReward\", _user)\n\treturn *ret0, err\n}", "func (_Smartchef *SmartchefTransactorSession) StopReward() (*types.Transaction, error) {\n\treturn _Smartchef.Contract.StopReward(&_Smartchef.TransactOpts)\n}", "func ApplyRewardTx(tx *types.Transaction, statedb *state.Statedb) (*types.Receipt, error) {\n\tstatedb.CreateAccount(tx.Data.To)\n\tstatedb.AddBalance(tx.Data.To, tx.Data.Amount)\n\n\thash, err := statedb.Hash()\n\tif err != nil {\n\t\treturn nil, errors.NewStackedError(err, \"failed to get statedb root hash\")\n\t}\n\n\treceipt := &types.Receipt{\n\t\tTxHash: tx.Hash,\n\t\tPostState: hash,\n\t}\n\n\treturn receipt, nil\n}", "func computeReward(epoch abi.ChainEpoch, prevTheta, currTheta, simpleTotal, baselineTotal big.Int) abi.TokenAmount {\n\tsimpleReward := big.Mul(simpleTotal, ExpLamSubOne) //Q.0 * Q.128 => Q.128\n\tepochLam := big.Mul(big.NewInt(int64(epoch)), Lambda) // Q.0 * Q.128 => Q.128\n\n\tsimpleReward = big.Mul(simpleReward, big.NewFromGo(math.ExpNeg(epochLam.Int))) // Q.128 * Q.128 => Q.256\n\tsimpleReward = big.Rsh(simpleReward, math.Precision128) // Q.256 >> 128 => Q.128\n\n\tbaselineReward := big.Sub(computeBaselineSupply(currTheta, baselineTotal), computeBaselineSupply(prevTheta, baselineTotal)) // Q.128\n\n\treward := big.Add(simpleReward, baselineReward) // Q.128\n\n\treturn big.Rsh(reward, math.Precision128) // Q.128 => Q.0\n}", "func (_Smartchef *SmartchefSession) StopReward() (*types.Transaction, error) {\n\treturn _Smartchef.Contract.StopReward(&_Smartchef.TransactOpts)\n}", "func (_Token *TokenCaller) CurrentReward(opts *bind.CallOpts, account common.Address) (struct {\n\tInitialDeposit *big.Int\n\tReward *big.Int\n}, error) {\n\tret := new(struct {\n\t\tInitialDeposit *big.Int\n\t\tReward *big.Int\n\t})\n\tout := ret\n\terr := _Token.contract.Call(opts, out, \"currentReward\", account)\n\treturn *ret, err\n}", "func (_XStaking *XStakingCaller) Rewards(opts *bind.CallOpts, arg0 common.Address) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _XStaking.contract.Call(opts, &out, \"rewards\", arg0)\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 (s *MutableState) AddRewardSingleAttenuated(time epochtime.EpochTime, factor *quantity.Quantity, attenuationNumerator, attenuationDenominator int, account signature.PublicKey) error {\n\tsteps, err := s.RewardSchedule()\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar activeStep *staking.RewardStep\n\tfor _, step := range steps {\n\t\tif time < step.Until {\n\t\t\tactiveStep = &step\n\t\t\tbreak\n\t\t}\n\t}\n\tif activeStep == nil {\n\t\t// We're past the end of the schedule.\n\t\treturn nil\n\t}\n\n\tvar numQ, denQ quantity.Quantity\n\tif err = numQ.FromInt64(int64(attenuationNumerator)); err != nil {\n\t\treturn errors.Wrapf(err, \"importing attenuation numerator %d\", attenuationNumerator)\n\t}\n\tif err = denQ.FromInt64(int64(attenuationDenominator)); err != nil {\n\t\treturn errors.Wrapf(err, \"importing attenuation denominator %d\", attenuationDenominator)\n\t}\n\n\tcommonPool, err := s.CommonPool()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"loading common pool\")\n\t}\n\n\tent := s.Account(account)\n\n\tq := ent.Escrow.Active.Balance.Clone()\n\t// Multiply first.\n\tif err := q.Mul(factor); err != nil {\n\t\treturn errors.Wrap(err, \"multiplying by reward factor\")\n\t}\n\tif err := q.Mul(&activeStep.Scale); err != nil {\n\t\treturn errors.Wrap(err, \"multiplying by reward step scale\")\n\t}\n\tif err := q.Mul(&numQ); err != nil {\n\t\treturn errors.Wrap(err, \"multiplying by attenuation numerator\")\n\t}\n\tif err := q.Quo(staking.RewardAmountDenominator); err != nil {\n\t\treturn errors.Wrap(err, \"dividing by reward amount denominator\")\n\t}\n\tif err := q.Quo(&denQ); err != nil {\n\t\treturn errors.Wrap(err, \"dividing by attenuation denominator\")\n\t}\n\n\tif q.IsZero() {\n\t\treturn nil\n\t}\n\n\tvar com *quantity.Quantity\n\trate := ent.Escrow.CommissionSchedule.CurrentRate(time)\n\tif rate != nil {\n\t\tcom = q.Clone()\n\t\t// Multiply first.\n\t\tif err := com.Mul(rate); err != nil {\n\t\t\treturn errors.Wrap(err, \"multiplying by commission rate\")\n\t\t}\n\t\tif err := com.Quo(staking.CommissionRateDenominator); err != nil {\n\t\t\treturn errors.Wrap(err, \"dividing by commission rate denominator\")\n\t\t}\n\n\t\tif err := q.Sub(com); err != nil {\n\t\t\treturn errors.Wrap(err, \"subtracting commission\")\n\t\t}\n\t}\n\n\tif !q.IsZero() {\n\t\tif err := quantity.Move(&ent.Escrow.Active.Balance, commonPool, q); err != nil {\n\t\t\treturn errors.Wrap(err, \"transferring to active escrow balance from common pool\")\n\t\t}\n\t}\n\n\tif com != nil && !com.IsZero() {\n\t\tdelegation := s.Delegation(account, account)\n\n\t\tif err := ent.Escrow.Active.Deposit(&delegation.Shares, commonPool, com); err != nil {\n\t\t\treturn errors.Wrap(err, \"depositing commission\")\n\t\t}\n\n\t\ts.SetDelegation(account, account, delegation)\n\t}\n\n\ts.SetAccount(account, ent)\n\n\ts.SetCommonPool(commonPool)\n\n\treturn nil\n}", "func (_Contract *ContractCaller) TaskHandlingReward(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Contract.contract.Call(opts, &out, \"taskHandlingReward\")\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 (d *Dao) UseReward(id int64, usePlat string) (rst bool, err error) {\n\tif err := d.orm.\n\t\tModel(&model.AnchorReward{}).\n\t\tWhere(\"id=?\", id).\n\t\tUpdate(map[string]interface{}{\"status\": model.RewardUsed, \"use_plat\": usePlat, \"use_time\": xtime.Time(time.Now().Unix())}).Error; err != nil {\n\t\tlog.Error(\"useReward (%v) error(%v)\", id, err)\n\t\treturn rst, err\n\t}\n\trst = true\n\treturn\n}", "func (s *BlocksService) Reward(ctx context.Context) (*BlocksReward, *http.Response, error) {\n\tvar responseStruct *BlocksReward\n\tresp, err := s.client.SendRequest(ctx, \"GET\", \"blocks/getReward\", nil, &responseStruct)\n\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn responseStruct, resp, err\n}", "func (c *Calculator) votingReward(\n\tmultiplier *big.Int,\n\tdivider *big.Int,\n\tfrom int,\n\tto int,\n\tprepInfo map[string]*pRepEnable,\n\titer icstate.VotingIterator,\n) *big.Int {\n\ttotal := new(big.Int)\n\tcheckMinVoting := c.global.GetIISSVersion() == icstate.IISSVersion2\n\tfor ; iter.Has(); iter.Next() {\n\t\tif voting, err := iter.Get(); err != nil {\n\t\t\tc.log.Errorf(\"Failed to iterate votings err=%+v\", err)\n\t\t} else {\n\t\t\tif checkMinVoting && voting.Amount().Cmp(BigIntMinDelegation) < 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ts := from\n\t\t\te := to\n\t\t\tif prep, ok := prepInfo[icutils.ToKey(voting.To())]; ok {\n\t\t\t\tif prep.StartOffset() != 0 && prep.StartOffset() > s {\n\t\t\t\t\ts = prep.StartOffset()\n\t\t\t\t}\n\t\t\t\tif prep.EndOffset() != 0 && prep.EndOffset() < e {\n\t\t\t\t\te = prep.EndOffset()\n\t\t\t\t}\n\t\t\t\tperiod := e - s\n\t\t\t\tif period <= 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\treward := new(big.Int).Mul(multiplier, voting.Amount())\n\t\t\t\treward.Mul(reward, big.NewInt(int64(period)))\n\t\t\t\treward.Div(reward, divider)\n\t\t\t\ttotal.Add(total, reward)\n\t\t\t\tc.log.Tracef(\"VotingReward %s: %s = %s * %s * %d / %s\",\n\t\t\t\t\tvoting.To(), reward, multiplier, voting.Amount(), period, divider)\n\t\t\t}\n\t\t}\n\t}\n\treturn total\n}", "func (owner *WalletOwnerAPI) PostTx(slate slateversions.SlateV4, fluff bool) error {\n\tparams := struct {\n\t\tToken string `json:\"token\"`\n\t\tSlate slateversions.SlateV4 `json:\"slate\"`\n\t\tFluff bool `json:\"fluff\"`\n\t}{\n\t\tToken: owner.token,\n\t\tSlate: slate,\n\t\tFluff: fluff,\n\t}\n\tparamsBytes, err := json.Marshal(params)\n\tif err != nil {\n\t\treturn err\n\t}\n\tenvl, err := owner.client.EncryptedRequest(\"post_tx\", paramsBytes, owner.sharedSecret)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif envl == nil {\n\t\treturn errors.New(\"WalletOwnerAPI: Empty RPC Response from grin-wallet\")\n\t}\n\tif envl.Error != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"code\": envl.Error.Code,\n\t\t\t\"message\": envl.Error.Message,\n\t\t}).Error(\"WalletOwnerAPI: RPC Error during PostTx\")\n\t\treturn errors.New(string(envl.Error.Code) + \"\" + envl.Error.Message)\n\t}\n\tvar result Result\n\tif err = json.Unmarshal(envl.Result, &result); err != nil {\n\t\treturn err\n\t}\n\tif result.Err != nil {\n\t\treturn errors.New(string(result.Err))\n\t}\n\treturn nil\n}", "func (_Lmc *LmcCallerSession) GetUserRewardDebt(_userAddress common.Address, _index *big.Int) (*big.Int, error) {\n\treturn _Lmc.Contract.GetUserRewardDebt(&_Lmc.CallOpts, _userAddress, _index)\n}", "func (k Keeper) ClaimDelegatorReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tclaim, found := k.GetDelegatorClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tsyncedClaim, err := k.SynchronizeDelegatorClaim(ctx, claim)\n\tif err != nil {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr = k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetDelegatorClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func GetReward(a Action, feedback Action) float64 {\n\tif a == feedback {\n\t\treturn 1\n\t}\n\treturn -1\n}", "func (del Delegation) ClaimedReward() (hexutil.Big, error) {\n\tval, err := repository.R().RewardsClaimed(&del.Address, (*big.Int)(del.Delegation.ToStakerId), nil, nil)\n\tif err != nil {\n\t\treturn hexutil.Big{}, err\n\t}\n\treturn (hexutil.Big)(*val), nil\n}", "func (k Keeper) ClaimUSDXMintingReward(ctx sdk.Context, owner, receiver sdk.AccAddress, multiplierName string) error {\n\tclaim, found := k.GetUSDXMintingClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, types.USDXMintingRewardDenom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", types.USDXMintingRewardDenom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tclaim, err := k.SynchronizeUSDXMintingClaim(ctx, claim)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trewardAmount := sdk.NewDecFromInt(claim.Reward.Amount).Mul(multiplier.Factor).RoundInt()\n\tif rewardAmount.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\trewardCoin := sdk.NewCoin(claim.Reward.Denom, rewardAmount)\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr = k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, sdk.NewCoins(rewardCoin), length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tk.ZeroUSDXMintingClaim(ctx, claim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claim.Reward.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, claim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func (_Lmc *LmcSession) GetUserRewardDebt(_userAddress common.Address, _index *big.Int) (*big.Int, error) {\n\treturn _Lmc.Contract.GetUserRewardDebt(&_Lmc.CallOpts, _userAddress, _index)\n}", "func (_Smartchef *SmartchefCallerSession) PendingReward(_user common.Address) (*big.Int, error) {\n\treturn _Smartchef.Contract.PendingReward(&_Smartchef.CallOpts, _user)\n}", "func (_Smartchef *SmartchefSession) PendingReward(_user common.Address) (*big.Int, error) {\n\treturn _Smartchef.Contract.PendingReward(&_Smartchef.CallOpts, _user)\n}", "func (_XStaking *XStakingTransactorSession) NotifyRewardAmount(reward *big.Int) (*types.Transaction, error) {\n\treturn _XStaking.Contract.NotifyRewardAmount(&_XStaking.TransactOpts, reward)\n}", "func (_Token *TokenSession) CurrentReward(account common.Address) (struct {\n\tInitialDeposit *big.Int\n\tReward *big.Int\n}, error) {\n\treturn _Token.Contract.CurrentReward(&_Token.CallOpts, account)\n}", "func (c RewardsController) CollectReward(id string) revel.Result {\n\tif !c.GetCurrentUser() {\n\t\treturn c.ForbiddenResponse()\n\t}\n\n\tif !bson.IsObjectIdHex(id) {\n\t\treturn c.ErrorResponse(nil, c.Message(\"error.invalid\", \"\"), core.ModelStatus[core.StatusInvalidID])\n\t}\n\n\tvar selector = []bson.M{\n\t\tbson.M{\"user_id\": c.CurrentUser.GetID().Hex()},\n\t\tbson.M{\"_id\": id},\n\t\tbson.M{\"multi\": false},\n\t}\n\tvar query = bson.M{\"$set\": []bson.M{\n\t\tbson.M{\"status.name\": core.StatusObtained},\n\t\tbson.M{\"status.code\": core.ValidationStatus[core.StatusObtained]},\n\t}}\n\n\t// Get pending Rewards for the user\n\tif Reward, ok := app.Mapper.GetModel(&models.Reward{}); ok {\n\t\tif err := Reward.UpdateQuery(selector, query, false); err != nil {\n\t\t\trevel.ERROR.Print(\"ERROR Find\")\n\t\t\treturn c.ErrorResponse(err, err.Error(), 400)\n\t\t}\n\t\treturn c.SuccessResponse(bson.M{\"data\": \"Reward collected successfully\"}, \"success\", core.ModelsType[core.ModelSimpleResponse], nil)\n\t}\n\n\treturn c.ServerErrorResponse()\n}", "func (_XStaking *XStakingSession) NotifyRewardAmount(reward *big.Int) (*types.Transaction, error) {\n\treturn _XStaking.Contract.NotifyRewardAmount(&_XStaking.TransactOpts, reward)\n}", "func (_Lmc *LmcCaller) GetUserRewardDebt(opts *bind.CallOpts, _userAddress common.Address, _index *big.Int) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Lmc.contract.Call(opts, &out, \"getUserRewardDebt\", _userAddress, _index)\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 (_RewardsDistributionRecipient *RewardsDistributionRecipientSession) NotifyRewardAmount(reward *big.Int) (*types.Transaction, error) {\n\treturn _RewardsDistributionRecipient.Contract.NotifyRewardAmount(&_RewardsDistributionRecipient.TransactOpts, reward)\n}", "func (_RewardsDistributionRecipient *RewardsDistributionRecipientTransactorSession) NotifyRewardAmount(reward *big.Int) (*types.Transaction, error) {\n\treturn _RewardsDistributionRecipient.Contract.NotifyRewardAmount(&_RewardsDistributionRecipient.TransactOpts, reward)\n}", "func postAnswer(c *gin.Context) {\n\tplayer := c.PostForm(\"player\")\n\tslide, err := strconv.Atoi(c.Param(\"slide\"))\n\tif err != nil {\n\t\tc.String(http.StatusBadRequest, fmt.Sprintf(\"Invalid slide param: %v: %v\", c.Param(\"slide\"), err))\n\t\treturn\n\t}\n\tanswer, err := strconv.Atoi(c.PostForm(\"answer\"))\n\tif err != nil {\n\t\tc.String(http.StatusBadRequest, fmt.Sprintf(\"Invalid answer param: %v: %v\", c.PostForm(\"answer\"), err))\n\t\treturn\n\t}\n\n\tmessage := fmt.Sprintf(\"%v answered slide %v with %v\", player, slide, answer)\n\tfmt.Println(message)\n\n\t// add player if they don't exist\n\t_, found := game_data.FindPlayer(player)\n\tif !found {\n\t\tgame_data.AddPlayer(trivia.Player{Name: player})\n\t}\n\n\tif err := game_data.AddAnswer(player, slide, answer); err != nil {\n\t\tc.String(http.StatusBadRequest, fmt.Sprintf(\"Could not set answer: %v: %v\", message, err))\n\t\treturn\n\t}\n\tmyGame(c, player)\n}", "func (_Contract *ContractCaller) TaskErasingReward(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Contract.contract.Call(opts, &out, \"taskErasingReward\")\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 (v *Vending) Post(c echo.Context) error {\n\trefill, err := strconv.Atoi(c.Param(\"amount\"))\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Please fill with chocolate\")\n\t}\n\tv.chocolate += refill\n\treturn c.String(http.StatusOK, \"Vending machine refilled\")\n}", "func post(withTransfer bool, color colored.Color, amount uint64,\n\trequesterKeyPair *ed25519.KeyPair, chain *solo.Chain, contractName string,\n\tfunctionName string, params ...interface{}) (dict.Dict, error) {\n\trequest := solo.NewCallParams(contractName, functionName, params...)\n\tif withTransfer {\n\t\trequest = request.WithTransfer(color, amount)\n\t} else {\n\t\trequest = request.WithTransfer(colored.IOTA, uint64(1))\n\t}\n\tresponse, err := chain.PostRequestSync(request, requesterKeyPair)\n\treturn response, err\n}", "func (_XStaking *XStakingTransactor) NotifyRewardAmount(opts *bind.TransactOpts, reward *big.Int) (*types.Transaction, error) {\n\treturn _XStaking.contract.Transact(opts, \"notifyRewardAmount\", reward)\n}", "func (k Keeper) DeleteReward(ctx sdk.Context, stakingCoinDenom string, farmerAcc sdk.AccAddress) {\n\tstore := ctx.KVStore(k.storeKey)\n\tstore.Delete(types.GetRewardKey(stakingCoinDenom, farmerAcc))\n\tstore.Delete(types.GetRewardByFarmerAndStakingCoinDenomIndexKey(farmerAcc, stakingCoinDenom))\n}", "func (s *Spammer) PostTransaction(tx *devnetvm.Transaction, clt evilwallet.Client) {\n\tif tx == nil {\n\t\ts.log.Debug(ErrTransactionIsNil)\n\t\ts.ErrCounter.CountError(ErrTransactionIsNil)\n\t}\n\tallSolid := s.handleSolidityForReuseOutputs(clt, tx)\n\tif !allSolid {\n\t\ts.log.Debug(ErrInputsNotSolid)\n\t\ts.ErrCounter.CountError(errors.WithMessagef(ErrInputsNotSolid, \"txID: %s\", tx.ID().Base58()))\n\t\treturn\n\t}\n\n\tif err := evilwallet.RateSetterSleep(clt, s.UseRateSetter); err != nil {\n\t\treturn\n\t}\n\ttxID, blockID, err := clt.PostTransaction(tx)\n\tif err != nil {\n\t\ts.log.Debug(ErrFailPostTransaction)\n\t\ts.ErrCounter.CountError(errors.WithMessage(ErrFailPostTransaction, err.Error()))\n\t\treturn\n\t}\n\tif s.EvilScenario.OutputWallet.Type() == evilwallet.Reuse {\n\t\ts.EvilWallet.SetTxOutputsSolid(tx.Essence().Outputs(), clt.URL())\n\t}\n\n\tcount := s.State.txSent.Add(1)\n\ts.log.Debugf(\"%s: Last transaction sent, ID: %s, txCount: %d\", blockID.Base58(), txID.Base58(), count)\n}", "func (c *Contract) Payback(ctx TransactionContextInterface, jeweler string, paperNumber string, paidbackDateTime string) (*InventoryFinancingPaper, error) {\r\n\tpaper, err := ctx.GetPaperList().GetPaper(jeweler, paperNumber)\r\n\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\tif paper.IsPaidBack() {\r\n\t\treturn nil, fmt.Errorf(\"paper %s:%s is already PaidBack\", jeweler, paperNumber)\r\n\t}\r\n\r\n\tpaper.SetPaidBack()\r\n\r\n\terr = ctx.GetPaperList().UpdatePaper(paper)\r\n\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\tfmt.Printf(\"inventory paper %q:%q is paid back by %q,The paidback date is %q. Current state = %q\", jeweler, paperNumber, jeweler, paidbackDateTime, paper.GetState())\r\n\treturn paper, nil\r\n}", "func (msg MsgClaimUSDXMintingReward) Type() string { return TypeMsgClaimUSDXMintingReward }", "func (_Token *TokenCallerSession) CurrentReward(account common.Address) (struct {\n\tInitialDeposit *big.Int\n\tReward *big.Int\n}, error) {\n\treturn _Token.Contract.CurrentReward(&_Token.CallOpts, account)\n}", "func (k Querier) Rewards(c context.Context, req *types.QueryRewardsRequest) (*types.QueryRewardsResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"invalid request\")\n\t}\n\n\tif req.StakingCoinDenom != \"\" {\n\t\tif err := sdk.ValidateDenom(req.StakingCoinDenom); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tctx := sdk.UnwrapSDKContext(c)\n\tstore := ctx.KVStore(k.storeKey)\n\tvar rewards []types.Reward\n\tvar pageRes *query.PageResponse\n\tvar err error\n\n\tif req.Farmer != \"\" {\n\t\tvar farmerAcc sdk.AccAddress\n\t\tfarmerAcc, err = sdk.AccAddressFromBech32(req.Farmer)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tstorePrefix := types.GetRewardsByFarmerIndexKey(farmerAcc)\n\t\tindexStore := prefix.NewStore(store, storePrefix)\n\t\tpageRes, err = query.FilteredPaginate(indexStore, req.Pagination, func(key, value []byte, accumulate bool) (bool, error) {\n\t\t\t_, stakingCoinDenom := types.ParseRewardsByFarmerIndexKey(append(storePrefix, key...))\n\t\t\tif req.StakingCoinDenom != \"\" {\n\t\t\t\tif stakingCoinDenom != req.StakingCoinDenom {\n\t\t\t\t\treturn false, nil\n\t\t\t\t}\n\t\t\t}\n\t\t\treward, found := k.GetReward(ctx, stakingCoinDenom, farmerAcc)\n\t\t\tif !found { // TODO: remove this check\n\t\t\t\treturn false, fmt.Errorf(\"reward not found\")\n\t\t\t}\n\t\t\tif accumulate {\n\t\t\t\trewards = append(rewards, reward)\n\t\t\t}\n\t\t\treturn true, nil\n\t\t})\n\t} else {\n\t\tvar storePrefix []byte\n\t\tif req.StakingCoinDenom != \"\" {\n\t\t\tstorePrefix = types.GetRewardsByStakingCoinDenomKey(req.StakingCoinDenom)\n\t\t} else {\n\t\t\tstorePrefix = types.RewardKeyPrefix\n\t\t}\n\t\trewardStore := prefix.NewStore(store, storePrefix)\n\n\t\tpageRes, err = query.Paginate(rewardStore, req.Pagination, func(key, value []byte) error {\n\t\t\tstakingCoinDenom, farmerAcc := types.ParseRewardKey(append(storePrefix, key...))\n\t\t\trewardCoins, err := k.UnmarshalRewardCoins(value)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\trewards = append(rewards, types.Reward{\n\t\t\t\tFarmer: farmerAcc.String(),\n\t\t\t\tStakingCoinDenom: stakingCoinDenom,\n\t\t\t\tRewardCoins: rewardCoins.RewardCoins,\n\t\t\t})\n\t\t\treturn nil\n\t\t})\n\t}\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &types.QueryRewardsResponse{Rewards: rewards, Pagination: pageRes}, nil\n}", "func (client CloudEndpointsClient) PostRestoreResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (_IStakingRewards *IStakingRewardsTransactor) GetReward(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _IStakingRewards.contract.Transact(opts, \"getReward\")\n}", "func (tf TestFixture) PostTest(ctx context.Context, s *testing.FixtTestState) {\n}", "func sendMsgAddPostReaction(\n\tr *rand.Rand, app *baseapp.BaseApp, ak authkeeper.AccountKeeper, bk bankkeeper.Keeper,\n\tmsg *types.MsgAddPostReaction, ctx sdk.Context, chainID string, privkeys []cryptotypes.PrivKey,\n) error {\n\taddr, _ := sdk.AccAddressFromBech32(msg.User)\n\taccount := ak.GetAccount(ctx, addr)\n\tcoins := bk.SpendableCoins(ctx, account.GetAddress())\n\n\tfees, err := simtypes.RandomFees(r, ctx, coins)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttxGen := simappparams.MakeTestEncodingConfig().TxConfig\n\ttx, err := helpers.GenTx(\n\t\ttxGen,\n\t\t[]sdk.Msg{msg},\n\t\tfees,\n\t\tDefaultGasValue,\n\t\tchainID,\n\t\t[]uint64{account.GetAccountNumber()},\n\t\t[]uint64{account.GetSequence()},\n\t\tprivkeys...,\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, _, err = app.Deliver(txGen.TxEncoder(), tx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (t *Transaction) Reward() string {\n\treturn t.reward\n}", "func (_IStakingRewards *IStakingRewardsTransactorSession) GetReward() (*types.Transaction, error) {\n\treturn _IStakingRewards.Contract.GetReward(&_IStakingRewards.TransactOpts)\n}", "func (c *GetUserPostClosestController) Post() {\n\tc.EnableXSRF = false\n\n\tcookiekey := beego.AppConfig.String(\"passid\")\n\n\t//get from cache\n\tpassId, _ := c.GetSecureCookie(cookiekey, \"passid\")\n\tif len(passId) <= 0 {\n\t\tpassId = c.GetString(\"passid\", \"\")\n\t\tif len(passId) < 1{\n\t\t\toutput, _ := library.ReturnJsonWithError(library.GetUserFail, \"ref\", nil)\n\t\t\tc.Ctx.WriteString(output)\n\t\t\treturn\n\t\t}\n\t}\n\tcahchedUser, err := models.GetUserFromCache(passId, true)\n\tif err != nil {\n\t\toutput, _ := library.ReturnJsonWithError(library.GetUserFail, \"ref\", err.Error())\n\t\tc.Ctx.WriteString(output)\n\t\treturn\n\t}\n\tuid := cahchedUser.UserProfile.Id\n\n\toption := c.GetString(\"option\")\n\tvar isNext bool = false\n\tif option == \"next\"{\n\t\tisNext = true\n\t}\n\tdate := c.GetString(\"date\")\n\tdateCorrect := strings.Replace(date, \"/\", \"\", -1)\n\tintDate ,_ := strconv.Atoi(dateCorrect)\n\tvar newPostDb = models.NewPost()\n\t//var getUser = newUser.GetUserProfile()\n\t//logs.Warning(getUser)\n\tpostList, err := newPostDb.GetUserClosestPost(uid, intDate, isNext)\n\n\tvar output string\n\n\tif err != nil{\n\t\toutput, _ = library.ReturnJsonWithError(library.CodeErrCommen, err.Error(), nil)\n\n\t}else {\n\t\toutput, _ = library.ReturnJsonWithError(library.CodeSucc, \"ref\", postList)\n\t}\n\n\tc.Ctx.WriteString(output)\n}", "func (_IStakingRewards *IStakingRewardsTransactorSession) Exit() (*types.Transaction, error) {\n\treturn _IStakingRewards.Contract.Exit(&_IStakingRewards.TransactOpts)\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactorSession) DistributeERC20Reward(_tokenAddress common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.DistributeERC20Reward(&_BondedECDSAKeep.TransactOpts, _tokenAddress, _value)\n}", "func (m *MockPostDecorator) PostHandle(ctx types.Context, tx types.Tx, simulate, success bool, next types.PostHandler) (types.Context, error) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"PostHandle\", ctx, tx, simulate, success, next)\n\t// NOTE: we need to edit the generated code to call the \"next handler\"\n\treturn next(ctx, tx, simulate, success)\n}", "func (_Dospayment *DospaymentSession) ClaimGuardianReward(guardianAddr common.Address) (*types.Transaction, error) {\n\treturn _Dospayment.Contract.ClaimGuardianReward(&_Dospayment.TransactOpts, guardianAddr)\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactor) DistributeERC20Reward(opts *bind.TransactOpts, _tokenAddress common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.contract.Transact(opts, \"distributeERC20Reward\", _tokenAddress, _value)\n}", "func (s *BasemumpsListener) EnterPostcondition(ctx *PostconditionContext) {}", "func (_Dospayment *DospaymentTransactorSession) ClaimGuardianReward(guardianAddr common.Address) (*types.Transaction, error) {\n\treturn _Dospayment.Contract.ClaimGuardianReward(&_Dospayment.TransactOpts, guardianAddr)\n}", "func MoveBtcCoinRewardNumber(btcidx int64) int64 {\n\tvar lvn = 21\n\tif btcidx == 1 {\n\t\treturn powf2(lvn - 1)\n\t}\n\tif btcidx > powf2(lvn)-1 {\n\t\treturn 1 // Finally, always issue an additional one\n\t}\n\tvar tarlv int\n\tfor i := 0; i < lvn; i++ {\n\t\tl := powf2(i) - 1\n\t\tr := powf2(i+1) - 1\n\t\tif btcidx > l && btcidx <= r {\n\t\t\ttarlv = i + 1\n\t\t\tbreak\n\t\t}\n\t}\n\treturn powf2(lvn - tarlv)\n}", "func (s *PostSvc) RmvPost(ctx context.Context, req *pb.RmvPostReq) (*pb.RmvPostResp, error) {\n\treturn s.db.RmvPost(ctx, req)\n}", "func (_BondedECDSAKeep *BondedECDSAKeepSession) DistributeERC20Reward(_tokenAddress common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.DistributeERC20Reward(&_BondedECDSAKeep.TransactOpts, _tokenAddress, _value)\n}", "func ValidateRewardTx(tx *types.Transaction, header *types.BlockHeader) error {\n\tif tx.Data.Type != types.TxTypeReward || !tx.Data.From.IsEmpty() || tx.Data.AccountNonce != 0 || tx.Data.GasPrice.Cmp(common.Big0) != 0 || tx.Data.GasLimit != 0 || len(tx.Data.Payload) != 0 {\n\t\treturn errInvalidReward\n\t}\n\n\t// validate to address\n\tto := tx.Data.To\n\tif to.IsEmpty() {\n\t\treturn errEmptyToAddress\n\t}\n\n\tif !to.Equal(header.Creator) {\n\t\treturn errCoinbaseMismatch\n\t}\n\n\t// validate reward\n\tamount := tx.Data.Amount\n\tif err := validateReward(amount); err != nil {\n\t\treturn err\n\t}\n\n\treward := consensus.GetReward(header.Height)\n\tif reward == nil || reward.Cmp(amount) != 0 {\n\t\treturn fmt.Errorf(\"invalid reward Amount, block height %d, want %s, got %s\", header.Height, reward, amount)\n\t}\n\n\t// validate timestamp\n\tif tx.Data.Timestamp != header.CreateTimestamp.Uint64() {\n\t\treturn errTimestampMismatch\n\t}\n\n\treturn nil\n}", "func (transaction *AccountCreateTransaction) SetDeclineStakingReward(decline bool) *AccountCreateTransaction {\n\ttransaction._RequireNotFrozen()\n\ttransaction.declineReward = decline\n\treturn transaction\n}", "func (_IStakingRewards *IStakingRewardsSession) GetReward() (*types.Transaction, error) {\n\treturn _IStakingRewards.Contract.GetReward(&_IStakingRewards.TransactOpts)\n}", "func (_Lmc *LmcCaller) GetUserAccumulatedReward(opts *bind.CallOpts, _userAddress common.Address, tokenIndex *big.Int) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Lmc.contract.Call(opts, &out, \"getUserAccumulatedReward\", _userAddress, tokenIndex)\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 (am *AS3Manager) postAgentResponse(msgRsp MessageResponse) {\n\tselect {\n\tcase am.RspChan <- msgRsp:\n\tcase <-am.RspChan:\n\t\tam.RspChan <- msgRsp\n\t}\n}", "func (am *AS3Manager) postAgentResponse(msgRsp MessageResponse) {\n\tselect {\n\tcase am.RspChan <- msgRsp:\n\tcase <-am.RspChan:\n\t\tam.RspChan <- msgRsp\n\t}\n}", "func (_IStakingRewards *IStakingRewardsCaller) LastTimeRewardApplicable(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _IStakingRewards.contract.Call(opts, &out, \"lastTimeRewardApplicable\")\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 (k Keeper) ClaimHardReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tk.SynchronizeHardLiquidityProviderClaim(ctx, owner)\n\n\tsyncedClaim, found := k.GetHardLiquidityProviderClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr := k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetHardLiquidityProviderClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func (_Smartchef *SmartchefCaller) RewardPerBlock(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Smartchef.contract.Call(opts, out, \"rewardPerBlock\")\n\treturn *ret0, err\n}", "func (e *EvaluationHandler) PostTestResult(c *gin.Context) {\n\t// User session\n\tloggedIn := e.Middleware.GetLoggedInUser(c)\n\n\t// Result\n\tresult := e.EvaluationUsecase.PostTestResult(loggedIn.Username)\n\n\t// Post test status\n\tpostTestStatus := 1\n\tcourses := e.LearningUsecase.GetCourseList()\n\tfor _, course := range courses {\n\t\t_, statusCode := course.GetParticipantStatus(loggedIn.Username)\n\t\tif statusCode < 2 {\n\t\t\tpostTestStatus = 0\n\t\t}\n\t}\n\n\t// User complete past test\n\tcertificate := \"\"\n\tif result.Pass && postTestStatus == 1 {\n\t\tpostTestStatus = 2\n\t\tcertificate = \"Coursera%20XZS4R52UDZFN.pdf\"\n\t}\n\n\t// Response\n\tgrade := fmt.Sprintf(\"%.f\", result.Grade)\n\tmsg := \"To Pass get 80%\"\n\tres := PostTestResultResponse{\n\t\tGrade: grade + \"%\",\n\t\tPass: result.Pass,\n\t\tStatus: postTestStatus,\n\t\tCertificateUrl: certificate,\n\t}\n\tresponse.RespondSuccessJSON(c.Writer, res, msg)\n}", "func (c4 *Connect4) GetReward() int {\n\tif c4.Winner == nil {\n\t\treturn 0\n\t} else if *c4.Winner == 1 {\n\t\treturn 1\n\t}\n\treturn -1\n}", "func (client ManagementClient) PostUserRequestaudittrailResponder(resp *http.Response) (result autorest.Response, err error) {\n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK),\n autorest.ByClosing())\n result.Response = resp\n return\n }", "func (_XStaking *XStakingTransactor) GetReward(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _XStaking.contract.Transact(opts, \"getReward\")\n}", "func (_Contract *ContractCallerSession) TaskHandlingReward() (*big.Int, error) {\n\treturn _Contract.Contract.TaskHandlingReward(&_Contract.CallOpts)\n}", "func (_RewardsDistributionRecipient *RewardsDistributionRecipientTransactor) NotifyRewardAmount(opts *bind.TransactOpts, reward *big.Int) (*types.Transaction, error) {\n\treturn _RewardsDistributionRecipient.contract.Transact(opts, \"notifyRewardAmount\", reward)\n}", "func redeem (stub shim.ChaincodeStubInterface, args []string) ([]byte,error){\n\n\tif len(args) != 5 {\n\t\t\tfmt.Println(\" Incorrect number of arguments sent to redeem. Expecting 5. Received \" + strconv.Itoa(len(args)))\n\t\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting 5\")\n\t\t}\n\n\t\t_, err := LoyaltyPkg.RedeemPoints(stub, args)\n\n\tif err != nil {\n\n\t\tfmt.Println(err)\n\t\treturn nil, errors.New(\"Errors while creating wallet for user \" + args[0])\n\t}\n\n\tlogger.Info(\"Successfully redeemed points for user \" + args[0])\n\n\treturn nil, nil\n\n}", "func (client ManagementClient) PostUserRefreshtokenforuseraccountResponder(resp *http.Response) (result autorest.Response, err error) {\n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK),\n autorest.ByClosing())\n result.Response = resp\n return\n }", "func (_Ethdkg *EthdkgTransactor) SubmitDispute(opts *bind.TransactOpts, issuer common.Address, issuer_list_idx *big.Int, disputer_list_idx *big.Int, encrypted_shares []*big.Int, commitments [][2]*big.Int, shared_key [2]*big.Int, shared_key_correctness_proof [2]*big.Int) (*types.Transaction, error) {\n\treturn _Ethdkg.contract.Transact(opts, \"submit_dispute\", issuer, issuer_list_idx, disputer_list_idx, encrypted_shares, commitments, shared_key, shared_key_correctness_proof)\n}", "func (_XStaking *XStakingCaller) RewardRate(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _XStaking.contract.Call(opts, &out, \"rewardRate\")\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 *Builder) StartPost(ctx context.Context, rewardAddress types.Address, dataDir string, space uint64) error {\n\tlogger := b.log.WithContext(ctx)\n\tif !atomic.CompareAndSwapInt32(&b.initStatus, InitIdle, InitInProgress) {\n\t\tswitch atomic.LoadInt32(&b.initStatus) {\n\t\tcase InitDone:\n\t\t\treturn fmt.Errorf(\"already initialized\")\n\t\tcase InitInProgress:\n\t\t\treturn fmt.Errorf(\"already started\")\n\t\t}\n\t}\n\n\tif err := b.postProver.SetParams(dataDir, space); err != nil {\n\t\treturn err\n\t}\n\tb.SetCoinbaseAccount(rewardAddress)\n\n\tinitialized, _, err := b.postProver.IsInitialized()\n\tif err != nil {\n\t\tatomic.StoreInt32(&b.initStatus, InitIdle)\n\t\treturn err\n\t}\n\n\tif !initialized {\n\t\tif err := b.postProver.VerifyInitAllowed(); err != nil {\n\t\t\tatomic.StoreInt32(&b.initStatus, InitIdle)\n\t\t\treturn err\n\t\t}\n\t}\n\n\tlogger.With().Info(\"starting post initialization\",\n\t\tlog.String(\"datadir\", dataDir),\n\t\tlog.String(\"space\", fmt.Sprintf(\"%d\", space)),\n\t\tlog.String(\"rewardAddress\", fmt.Sprintf(\"%x\", rewardAddress)),\n\t)\n\n\tgo func() {\n\t\tif initialized {\n\t\t\t// If initialized, run the execution phase with zero-challenge,\n\t\t\t// to create the initial proof (the commitment).\n\t\t\tb.commitment, err = b.postProver.Execute(shared.ZeroChallenge)\n\t\t\tif err != nil {\n\t\t\t\tlogger.With().Error(\"post execution failed\", log.Err(err))\n\t\t\t\tatomic.StoreInt32(&b.initStatus, InitIdle)\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\t// If not initialized, run the initialization phase.\n\t\t\t// This would create the initial proof (the commitment) as well.\n\t\t\tb.commitment, err = b.postProver.Initialize()\n\t\t\tif err != nil {\n\t\t\t\tlogger.With().Error(\"post initialization failed\", log.Err(err))\n\t\t\t\tatomic.StoreInt32(&b.initStatus, InitIdle)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tlogger.With().Info(\"post initialization completed\",\n\t\t\tlog.String(\"datadir\", dataDir),\n\t\t\tlog.String(\"space\", fmt.Sprintf(\"%d\", space)),\n\t\t\tlog.String(\"commitment merkle root\", fmt.Sprintf(\"%x\", b.commitment.MerkleRoot)),\n\t\t)\n\n\t\tatomic.StoreInt32(&b.initStatus, InitDone)\n\t\tclose(b.initDone)\n\t}()\n\n\treturn nil\n}" ]
[ "0.7498109", "0.6607101", "0.5900165", "0.574824", "0.5748048", "0.5657382", "0.5594524", "0.5589504", "0.55825084", "0.54884845", "0.54612577", "0.525241", "0.5206265", "0.5183272", "0.5154278", "0.5114508", "0.510423", "0.5094205", "0.5076016", "0.5053601", "0.5036061", "0.5011486", "0.50109583", "0.49988496", "0.49979222", "0.49852508", "0.49648166", "0.49568868", "0.49563044", "0.4950898", "0.494989", "0.4947571", "0.4938006", "0.49285802", "0.492693", "0.48947155", "0.48879582", "0.4877172", "0.4859275", "0.48472297", "0.48414806", "0.48300937", "0.4822483", "0.4814368", "0.47971287", "0.47770178", "0.47758803", "0.4770533", "0.47610724", "0.47584832", "0.47434106", "0.47418407", "0.47324914", "0.47269446", "0.47238335", "0.4720381", "0.47202805", "0.47197434", "0.47197115", "0.47119817", "0.46994978", "0.46976933", "0.46962345", "0.4693751", "0.4689654", "0.4685987", "0.467774", "0.46753466", "0.46740383", "0.46686044", "0.4664151", "0.4660877", "0.46599", "0.4653724", "0.4649478", "0.46435764", "0.4640306", "0.4639294", "0.46145603", "0.46028376", "0.45844007", "0.45768958", "0.4575707", "0.45695782", "0.45616046", "0.45616046", "0.45600158", "0.45588917", "0.4551121", "0.45502904", "0.45496023", "0.45460382", "0.45449683", "0.45362064", "0.4526416", "0.45238832", "0.4514642", "0.45107612", "0.45067087", "0.450342" ]
0.85944164
0
postReward encumbers a previouslydeposited reward according to the current vesting apportionment of staking. Note that rewards might be unvested, but are unlocked.
postReward привязывает ранее депонированные награды в соответствии с текущим распределением постепенного раскрытия стейкинга. Обратите внимание, что награды могут быть непривязанными, но доступны.
func (va ClawbackVestingAccount) postReward(ctx sdk.Context, reward sdk.Coins, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) { // Find the scheduled amount of vested and unvested staking tokens bondDenom := sk.BondDenom(ctx) vested := ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, ctx.BlockTime().Unix()).AmountOf(bondDenom) unvested := va.OriginalVesting.AmountOf(bondDenom).Sub(vested) if unvested.IsZero() { // no need to adjust the vesting schedule return } if vested.IsZero() { // all staked tokens must be unvested va.distributeReward(ctx, ak, bondDenom, reward) return } // Find current split of account balance on staking axis bonded := sk.GetDelegatorBonded(ctx, va.GetAddress()) unbonding := sk.GetDelegatorUnbonding(ctx, va.GetAddress()) delegated := bonded.Add(unbonding) // discover what has been slashed and remove from delegated amount oldDelegated := va.DelegatedVesting.AmountOf(bondDenom).Add(va.DelegatedFree.AmountOf(bondDenom)) slashed := oldDelegated.Sub(intMin(oldDelegated, delegated)) delegated = delegated.Sub(intMin(delegated, slashed)) // Prefer delegated tokens to be unvested unvested = intMin(unvested, delegated) vested = delegated.Sub(unvested) // Compute the unvested amount of reward and add to vesting schedule if unvested.IsZero() { return } if vested.IsZero() { va.distributeReward(ctx, ak, bondDenom, reward) return } unvestedRatio := unvested.ToDec().QuoTruncate(bonded.ToDec()) // round down unvestedReward := scaleCoins(reward, unvestedRatio) va.distributeReward(ctx, ak, bondDenom, unvestedReward) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (va *ClawbackVestingAccount) PostReward(ctx sdk.Context, reward sdk.Coins, action exported.RewardAction) error {\n\treturn action.ProcessReward(ctx, reward, va)\n}", "func (va ClawbackVestingAccount) distributeReward(ctx sdk.Context, ak AccountKeeper, bondDenom string, reward sdk.Coins) {\n\tnow := ctx.BlockTime().Unix()\n\tt := va.StartTime\n\tfirstUnvestedPeriod := 0\n\tunvestedTokens := sdk.ZeroInt()\n\tfor i, period := range va.VestingPeriods {\n\t\tt += period.Length\n\t\tif t <= now {\n\t\t\tfirstUnvestedPeriod = i + 1\n\t\t\tcontinue\n\t\t}\n\t\tunvestedTokens = unvestedTokens.Add(period.Amount.AmountOf(bondDenom))\n\t}\n\n\trunningTotReward := sdk.NewCoins()\n\trunningTotStaking := sdk.ZeroInt()\n\tfor i := firstUnvestedPeriod; i < len(va.VestingPeriods); i++ {\n\t\tperiod := va.VestingPeriods[i]\n\t\trunningTotStaking = runningTotStaking.Add(period.Amount.AmountOf(bondDenom))\n\t\trunningTotRatio := runningTotStaking.ToDec().Quo(unvestedTokens.ToDec())\n\t\ttargetCoins := scaleCoins(reward, runningTotRatio)\n\t\tthisReward := targetCoins.Sub(runningTotReward)\n\t\trunningTotReward = targetCoins\n\t\tperiod.Amount = period.Amount.Add(thisReward...)\n\t\tva.VestingPeriods[i] = period\n\t}\n\n\tva.OriginalVesting = va.OriginalVesting.Add(reward...)\n\tak.SetAccount(ctx, &va)\n}", "func (a Actor) AwardBlockReward(rt vmr.Runtime, params *AwardBlockRewardParams) *adt.EmptyValue {\n\trt.ValidateImmediateCallerIs(builtin.SystemActorAddr)\n\tAssertMsg(rt.CurrentBalance().GreaterThanEqual(params.GasReward),\n\t\t\"actor current balance %v insufficient to pay gas reward %v\", rt.CurrentBalance(), params.GasReward)\n\n\tAssertMsg(params.TicketCount > 0, \"cannot give block reward for zero tickets\")\n\n\tminer, ok := rt.ResolveAddress(params.Miner)\n\tif !ok {\n\t\trt.Abortf(exitcode.ErrIllegalState, \"failed to resolve given owner address\")\n\t}\n\n\tpriorBalance := rt.CurrentBalance()\n\n\tvar penalty abi.TokenAmount\n\tvar st State\n\trt.State().Transaction(&st, func() interface{} {\n\t\tblockReward := a.computeBlockReward(&st, big.Sub(priorBalance, params.GasReward), params.TicketCount)\n\t\ttotalReward := big.Add(blockReward, params.GasReward)\n\n\t\t// Cap the penalty at the total reward value.\n\t\tpenalty = big.Min(params.Penalty, totalReward)\n\n\t\t// Reduce the payable reward by the penalty.\n\t\trewardPayable := big.Sub(totalReward, penalty)\n\n\t\tAssertMsg(big.Add(rewardPayable, penalty).LessThanEqual(priorBalance),\n\t\t\t\"reward payable %v + penalty %v exceeds balance %v\", rewardPayable, penalty, priorBalance)\n\n\t\t// Record new reward into reward map.\n\t\tif rewardPayable.GreaterThan(abi.NewTokenAmount(0)) {\n\t\t\tnewReward := Reward{\n\t\t\t\tStartEpoch: rt.CurrEpoch(),\n\t\t\t\tEndEpoch: rt.CurrEpoch() + rewardVestingPeriod,\n\t\t\t\tValue: rewardPayable,\n\t\t\t\tAmountWithdrawn: abi.NewTokenAmount(0),\n\t\t\t\tVestingFunction: rewardVestingFunction,\n\t\t\t}\n\t\t\tif err := st.addReward(adt.AsStore(rt), miner, &newReward); err != nil {\n\t\t\t\trt.Abortf(exitcode.ErrIllegalState, \"failed to add reward to rewards map: %w\", err)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\n\t// Burn the penalty amount.\n\t_, code := rt.Send(builtin.BurntFundsActorAddr, builtin.MethodSend, nil, penalty)\n\tbuiltin.RequireSuccess(rt, code, \"failed to send penalty to BurntFundsActor\")\n\n\treturn nil\n}", "func (s *Spammer) PostTransaction(tx *devnetvm.Transaction, clt evilwallet.Client) {\n\tif tx == nil {\n\t\ts.log.Debug(ErrTransactionIsNil)\n\t\ts.ErrCounter.CountError(ErrTransactionIsNil)\n\t}\n\tallSolid := s.handleSolidityForReuseOutputs(clt, tx)\n\tif !allSolid {\n\t\ts.log.Debug(ErrInputsNotSolid)\n\t\ts.ErrCounter.CountError(errors.WithMessagef(ErrInputsNotSolid, \"txID: %s\", tx.ID().Base58()))\n\t\treturn\n\t}\n\n\tif err := evilwallet.RateSetterSleep(clt, s.UseRateSetter); err != nil {\n\t\treturn\n\t}\n\ttxID, blockID, err := clt.PostTransaction(tx)\n\tif err != nil {\n\t\ts.log.Debug(ErrFailPostTransaction)\n\t\ts.ErrCounter.CountError(errors.WithMessage(ErrFailPostTransaction, err.Error()))\n\t\treturn\n\t}\n\tif s.EvilScenario.OutputWallet.Type() == evilwallet.Reuse {\n\t\ts.EvilWallet.SetTxOutputsSolid(tx.Essence().Outputs(), clt.URL())\n\t}\n\n\tcount := s.State.txSent.Add(1)\n\ts.log.Debugf(\"%s: Last transaction sent, ID: %s, txCount: %d\", blockID.Base58(), txID.Base58(), count)\n}", "func (c *Client) RenterPostAllowance(allowance modules.Allowance) (err error) {\n\tvalues := url.Values{}\n\tvalues.Set(\"funds\", allowance.Funds.String())\n\tvalues.Set(\"hosts\", strconv.FormatUint(allowance.Hosts, 10))\n\tvalues.Set(\"period\", strconv.FormatUint(uint64(allowance.Period), 10))\n\tvalues.Set(\"renewwindow\", strconv.FormatUint(uint64(allowance.RenewWindow), 10))\n\terr = c.post(\"/renter\", values.Encode(), nil)\n\treturn\n}", "func post(withTransfer bool, color colored.Color, amount uint64,\n\trequesterKeyPair *ed25519.KeyPair, chain *solo.Chain, contractName string,\n\tfunctionName string, params ...interface{}) (dict.Dict, error) {\n\trequest := solo.NewCallParams(contractName, functionName, params...)\n\tif withTransfer {\n\t\trequest = request.WithTransfer(color, amount)\n\t} else {\n\t\trequest = request.WithTransfer(colored.IOTA, uint64(1))\n\t}\n\tresponse, err := chain.PostRequestSync(request, requesterKeyPair)\n\treturn response, err\n}", "func (owner *WalletOwnerAPI) PostTx(slate slateversions.SlateV4, fluff bool) error {\n\tparams := struct {\n\t\tToken string `json:\"token\"`\n\t\tSlate slateversions.SlateV4 `json:\"slate\"`\n\t\tFluff bool `json:\"fluff\"`\n\t}{\n\t\tToken: owner.token,\n\t\tSlate: slate,\n\t\tFluff: fluff,\n\t}\n\tparamsBytes, err := json.Marshal(params)\n\tif err != nil {\n\t\treturn err\n\t}\n\tenvl, err := owner.client.EncryptedRequest(\"post_tx\", paramsBytes, owner.sharedSecret)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif envl == nil {\n\t\treturn errors.New(\"WalletOwnerAPI: Empty RPC Response from grin-wallet\")\n\t}\n\tif envl.Error != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"code\": envl.Error.Code,\n\t\t\t\"message\": envl.Error.Message,\n\t\t}).Error(\"WalletOwnerAPI: RPC Error during PostTx\")\n\t\treturn errors.New(string(envl.Error.Code) + \"\" + envl.Error.Message)\n\t}\n\tvar result Result\n\tif err = json.Unmarshal(envl.Result, &result); err != nil {\n\t\treturn err\n\t}\n\tif result.Err != nil {\n\t\treturn errors.New(string(result.Err))\n\t}\n\treturn nil\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactor) DistributeETHReward(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.contract.Transact(opts, \"distributeETHReward\")\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 (requestManager *RequestManager) PostWithTransfer(requesterKeyPair *ed25519.KeyPair, color colored.Color, amount uint64,\n\tchain *solo.Chain, contractName string, functionName string, params ...interface{}) (dict.Dict, error) {\n\tresponse, err := post(true, color, amount, requesterKeyPair, chain, contractName, functionName, params...)\n\treturn response, err\n}", "func ApplyRewardTx(tx *types.Transaction, statedb *state.Statedb) (*types.Receipt, error) {\n\tstatedb.CreateAccount(tx.Data.To)\n\tstatedb.AddBalance(tx.Data.To, tx.Data.Amount)\n\n\thash, err := statedb.Hash()\n\tif err != nil {\n\t\treturn nil, errors.NewStackedError(err, \"failed to get statedb root hash\")\n\t}\n\n\treceipt := &types.Receipt{\n\t\tTxHash: tx.Hash,\n\t\tPostState: hash,\n\t}\n\n\treturn receipt, nil\n}", "func (k Keeper) ClaimSwapReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tsyncedClaim, found := k.GetSynchronizedSwapClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr := k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetSwapClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func (transaction *AccountCreateTransaction) SetDeclineStakingReward(decline bool) *AccountCreateTransaction {\n\ttransaction._RequireNotFrozen()\n\ttransaction.declineReward = decline\n\treturn transaction\n}", "func (c *Coinbase) AddReward(output *Output) {\n\toutput.EncryptedMask = make([]byte, 1)\n\tc.Rewards = append(c.Rewards, output)\n}", "func (k Keeper) ClaimSavingsReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tk.SynchronizeSavingsClaim(ctx, owner)\n\n\tsyncedClaim, found := k.GetSavingsClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr := k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetSavingsClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func (_BondedECDSAKeep *BondedECDSAKeepSession) DistributeETHReward() (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.DistributeETHReward(&_BondedECDSAKeep.TransactOpts)\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactorSession) DistributeETHReward() (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.DistributeETHReward(&_BondedECDSAKeep.TransactOpts)\n}", "func (k Keeper) ClaimEarnReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tsyncedClaim, found := k.GetSynchronizedEarnClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr := k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetEarnClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func (s *MutableState) AddRewardSingleAttenuated(time epochtime.EpochTime, factor *quantity.Quantity, attenuationNumerator, attenuationDenominator int, account signature.PublicKey) error {\n\tsteps, err := s.RewardSchedule()\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar activeStep *staking.RewardStep\n\tfor _, step := range steps {\n\t\tif time < step.Until {\n\t\t\tactiveStep = &step\n\t\t\tbreak\n\t\t}\n\t}\n\tif activeStep == nil {\n\t\t// We're past the end of the schedule.\n\t\treturn nil\n\t}\n\n\tvar numQ, denQ quantity.Quantity\n\tif err = numQ.FromInt64(int64(attenuationNumerator)); err != nil {\n\t\treturn errors.Wrapf(err, \"importing attenuation numerator %d\", attenuationNumerator)\n\t}\n\tif err = denQ.FromInt64(int64(attenuationDenominator)); err != nil {\n\t\treturn errors.Wrapf(err, \"importing attenuation denominator %d\", attenuationDenominator)\n\t}\n\n\tcommonPool, err := s.CommonPool()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"loading common pool\")\n\t}\n\n\tent := s.Account(account)\n\n\tq := ent.Escrow.Active.Balance.Clone()\n\t// Multiply first.\n\tif err := q.Mul(factor); err != nil {\n\t\treturn errors.Wrap(err, \"multiplying by reward factor\")\n\t}\n\tif err := q.Mul(&activeStep.Scale); err != nil {\n\t\treturn errors.Wrap(err, \"multiplying by reward step scale\")\n\t}\n\tif err := q.Mul(&numQ); err != nil {\n\t\treturn errors.Wrap(err, \"multiplying by attenuation numerator\")\n\t}\n\tif err := q.Quo(staking.RewardAmountDenominator); err != nil {\n\t\treturn errors.Wrap(err, \"dividing by reward amount denominator\")\n\t}\n\tif err := q.Quo(&denQ); err != nil {\n\t\treturn errors.Wrap(err, \"dividing by attenuation denominator\")\n\t}\n\n\tif q.IsZero() {\n\t\treturn nil\n\t}\n\n\tvar com *quantity.Quantity\n\trate := ent.Escrow.CommissionSchedule.CurrentRate(time)\n\tif rate != nil {\n\t\tcom = q.Clone()\n\t\t// Multiply first.\n\t\tif err := com.Mul(rate); err != nil {\n\t\t\treturn errors.Wrap(err, \"multiplying by commission rate\")\n\t\t}\n\t\tif err := com.Quo(staking.CommissionRateDenominator); err != nil {\n\t\t\treturn errors.Wrap(err, \"dividing by commission rate denominator\")\n\t\t}\n\n\t\tif err := q.Sub(com); err != nil {\n\t\t\treturn errors.Wrap(err, \"subtracting commission\")\n\t\t}\n\t}\n\n\tif !q.IsZero() {\n\t\tif err := quantity.Move(&ent.Escrow.Active.Balance, commonPool, q); err != nil {\n\t\t\treturn errors.Wrap(err, \"transferring to active escrow balance from common pool\")\n\t\t}\n\t}\n\n\tif com != nil && !com.IsZero() {\n\t\tdelegation := s.Delegation(account, account)\n\n\t\tif err := ent.Escrow.Active.Deposit(&delegation.Shares, commonPool, com); err != nil {\n\t\t\treturn errors.Wrap(err, \"depositing commission\")\n\t\t}\n\n\t\ts.SetDelegation(account, account, delegation)\n\t}\n\n\ts.SetAccount(account, ent)\n\n\ts.SetCommonPool(commonPool)\n\n\treturn nil\n}", "func (as AccountStorage) SetReward(ctx sdk.Context, accKey types.AccountKey, reward *Reward) sdk.Error {\n\tstore := ctx.KVStore(as.key)\n\trewardByte, err := as.cdc.MarshalJSON(*reward)\n\tif err != nil {\n\t\treturn ErrFailedToMarshalReward(err)\n\t}\n\tstore.Set(getRewardKey(accKey), rewardByte)\n\treturn nil\n}", "func (cra clawbackRewardAction) ProcessReward(ctx sdk.Context, reward sdk.Coins, rawAccount exported.VestingAccount) error {\n\tcva, ok := rawAccount.(*ClawbackVestingAccount)\n\tif !ok {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrNotSupported, \"expected *ClawbackVestingAccount, got %T\", rawAccount)\n\t}\n\tcva.postReward(ctx, reward, cra.ak, cra.bk, cra.sk)\n\treturn nil\n}", "func (_Ethdkg *EthdkgTransactor) SubmitDispute(opts *bind.TransactOpts, issuer common.Address, issuer_list_idx *big.Int, disputer_list_idx *big.Int, encrypted_shares []*big.Int, commitments [][2]*big.Int, shared_key [2]*big.Int, shared_key_correctness_proof [2]*big.Int) (*types.Transaction, error) {\n\treturn _Ethdkg.contract.Transact(opts, \"submit_dispute\", issuer, issuer_list_idx, disputer_list_idx, encrypted_shares, commitments, shared_key, shared_key_correctness_proof)\n}", "func (k Keeper) ClaimUSDXMintingReward(ctx sdk.Context, owner, receiver sdk.AccAddress, multiplierName string) error {\n\tclaim, found := k.GetUSDXMintingClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, types.USDXMintingRewardDenom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", types.USDXMintingRewardDenom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tclaim, err := k.SynchronizeUSDXMintingClaim(ctx, claim)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trewardAmount := sdk.NewDecFromInt(claim.Reward.Amount).Mul(multiplier.Factor).RoundInt()\n\tif rewardAmount.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\trewardCoin := sdk.NewCoin(claim.Reward.Denom, rewardAmount)\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr = k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, sdk.NewCoins(rewardCoin), length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tk.ZeroUSDXMintingClaim(ctx, claim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claim.Reward.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, claim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func (v *Vending) Post(c echo.Context) error {\n\trefill, err := strconv.Atoi(c.Param(\"amount\"))\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Please fill with chocolate\")\n\t}\n\tv.chocolate += refill\n\treturn c.String(http.StatusOK, \"Vending machine refilled\")\n}", "func (rig *testRig) redeem_taker(checkStatus bool) error {\n\tmatchInfo := rig.matchInfo\n\tmatchInfo.db.takerRedeem = rig.redeem(matchInfo.taker, matchInfo.takerOID)\n\ttracker := rig.getTracker()\n\t// Check the match status\n\tif checkStatus {\n\t\tif tracker != nil {\n\t\t\treturn fmt.Errorf(\"expected match to be removed, found it, in status %v\", tracker.Status)\n\t\t}\n\t\terr := rig.checkResponse(matchInfo.taker, \"redeem\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func placeBet(ctx coretypes.Sandbox) error {\n\tctx.Event(\"placeBet\")\n\tparams := ctx.Params()\n\n\tstate := ctx.State()\n\n\t// if there are some bets locked, save the entropy derived immediately from it.\n\t// it is not predictable at the moment of locking and this saving makes it not playable later\n\t// entropy saved this way is derived (hashed) from the locking transaction hash\n\t// we do this trick to be able to deterministically check if smart contract is really fair.\n\t// The played color is a deterministic function of the hash of transaction which locked the bets\n\tif collections.NewArray(state, StateVarLockedBets).MustLen() > 0 {\n\t\tok := state.MustHas(StateVarEntropyFromLocking)\n\t\tif !ok {\n\t\t\tehv := ctx.GetEntropy()\n\t\t\tstate.Set(StateVarEntropyFromLocking, codec.EncodeHashValue(&ehv))\n\t\t}\n\t}\n\n\t// take input addresses of the request transaction. Must be exactly 1 otherwise.\n\t// Theoretically the transaction may have several addresses in inputs, then it is ignored\n\tsender := ctx.Caller()\n\n\t// look if there're some iotas left for the bet after minimum rewards are already taken.\n\t// Here we are accessing only the part of the UTXOs which the ones which are coming with the current request\n\tsum := ctx.IncomingTransfer().Balance(balance.ColorIOTA)\n\tif sum == 0 {\n\t\t// nothing to bet\n\t\treturn fmt.Errorf(\"placeBet: sum == 0: nothing to bet\")\n\t}\n\t// check if there's a Color variable among args. If not, ignore the request\n\tcol, ok, _ := codec.DecodeInt64(params.MustGet(ReqVarColor))\n\tif !ok {\n\t\treturn fmt.Errorf(\"wrong request, no Color specified\")\n\t}\n\tfirstBet := collections.NewArray(state, StateVarBets).MustLen() == 0\n\n\treqid := ctx.RequestID()\n\tbetInfo := &BetInfo{\n\t\tPlayer: sender,\n\t\tSum: sum,\n\t\treqId: reqid,\n\t\tColor: byte(col % NumColors),\n\t}\n\n\t// save the bet info in the array\n\tcollections.NewArray(state, StateVarBets).MustPush(encodeBetInfo(betInfo))\n\n\tctx.Event(fmt.Sprintf(\"Place bet: player: %s sum: %d color: %d req: %s\", sender.String(), sum, col, reqid.Short()))\n\n\terr := withPlayerStats(ctx, &betInfo.Player, func(ps *PlayerStats) {\n\t\tps.Bets += 1\n\t})\n\tif err != nil {\n\t\tctx.Log().Panicf(\"%v\", err)\n\t}\n\n\t// if it is the first bet in the array, send time locked 'LockBets' request to itself.\n\t// it will be time-locked by default for the next 2 minutes, the it will be processed by smart contract\n\tif firstBet {\n\t\tperiod, ok, _ := codec.DecodeInt64(state.MustGet(ReqVarPlayPeriodSec))\n\t\tif !ok || period < 10 {\n\t\t\tperiod = DefaultPlaySecondsAfterFirstBet\n\t\t}\n\n\t\tnextPlayTimestamp := (time.Duration(ctx.GetTimestamp())*time.Nanosecond + time.Duration(period)*time.Second).Nanoseconds()\n\t\tstate.Set(StateVarNextPlayTimestamp, codec.EncodeInt64(nextPlayTimestamp))\n\n\t\tctx.Event(fmt.Sprintf(\"PostRequestToSelfWithDelay period = %d\", period))\n\n\t\t// send the timelocked Lock request to self. TimeLock is for number of seconds taken from the state variable\n\t\t// By default it is 2 minutes, i.e. Lock request will be processed after 2 minutes.\n\t\tif ctx.PostRequest(coretypes.PostRequestParams{\n\t\t\tTargetContractID: ctx.ContractID(),\n\t\t\tEntryPoint: RequestLockBets,\n\t\t\tTimeLock: uint32(period),\n\t\t}) {\n\t\t\tctx.Event(fmt.Sprintf(\"play deadline is set after %d seconds\", period))\n\t\t} else {\n\t\t\tctx.Event(fmt.Sprintf(\"failed to set play deadline\"))\n\t\t}\n\t}\n\treturn nil\n}", "func (_Ethdkg *EthdkgSession) SubmitDispute(issuer common.Address, issuer_list_idx *big.Int, disputer_list_idx *big.Int, encrypted_shares []*big.Int, commitments [][2]*big.Int, shared_key [2]*big.Int, shared_key_correctness_proof [2]*big.Int) (*types.Transaction, error) {\n\treturn _Ethdkg.Contract.SubmitDispute(&_Ethdkg.TransactOpts, issuer, issuer_list_idx, disputer_list_idx, encrypted_shares, commitments, shared_key, shared_key_correctness_proof)\n}", "func (w *worker) postSideBlock(event blockchain.ChainSideEvent) {\n\tselect {\n\tcase w.chainSideCh <- event:\n\tcase <-w.exitCh:\n\t}\n}", "func Redeem(contract []byte, contractTx wire.MsgTx, secret []byte, currency string, autopublish bool) (api.RedeemResponse, error) {\n\tnetwork := RetrieveNetwork(currency)\n\tclient := GetRPCClient(currency)\n\n\tdefer func() {\n\t\tclient.Shutdown()\n\t\tclient.WaitForShutdown()\n\t}()\n\n\tpushes, err := txscript.ExtractAtomicSwapDataPushes(0, contract)\n\tif err != nil {\n\t\treturn api.RedeemResponse{\"\", \"\", struct{}{}, nil, 51200}, err\n\t}\n\tif pushes == nil {\n\t\treturn api.RedeemResponse{\"\", \"\", struct{}{}, nil, 51200}, errors.New(\"contract is not an atomic swap script recognized by this tool\")\n\t}\n\n\trecipientAddr, err := diviutil.NewAddressPubKeyHash(pushes.RecipientHash160[:], network)\n\tif err != nil {\n\t\treturn api.RedeemResponse{\"\", \"\", struct{}{}, nil, 51200}, err\n\t}\n\tcontractHash := diviutil.Hash160(contract)\n\tcontractOut := -1\n\tfor i, out := range contractTx.TxOut {\n\t\tsc, addrs, _, _ := txscript.ExtractPkScriptAddrs(out.PkScript, network)\n\t\tif sc == txscript.ScriptHashTy &&\n\t\t\tbytes.Equal(addrs[0].(*diviutil.AddressScriptHash).Hash160()[:], contractHash) {\n\t\t\tcontractOut = i\n\t\t\tbreak\n\t\t}\n\t}\n\tif contractOut == -1 {\n\t\treturn api.RedeemResponse{\"\", \"\", struct{}{}, nil, 51200}, errors.New(\"transaction does not contain a contract output\")\n\t}\n\n\taddr, err := RawChangeAddress(client, currency)\n\tif err != nil {\n\t\treturn api.RedeemResponse{\"\", \"\", struct{}{}, nil, 51200}, err\n\t}\n\toutScript, err := txscript.PayToAddrScript(addr)\n\tif err != nil {\n\t\treturn api.RedeemResponse{\"\", \"\", struct{}{}, nil, 51200}, err\n\t}\n\n\tcontractTxHash := contractTx.TxHash()\n\tcontractOutPoint := wire.OutPoint{\n\t\tHash: contractTxHash,\n\t\tIndex: uint32(contractOut),\n\t}\n\n\tfeePerKb, minFeePerKb, err := GetFees(client, currency)\n\tif err != nil {\n\t\treturn api.RedeemResponse{\"\", \"\", struct{}{}, nil, 51200}, err\n\t}\n\n\tredeemTx := wire.NewMsgTx(util.TXVersion)\n\tredeemTx.LockTime = uint32(pushes.LockTime)\n\tredeemTx.AddTxIn(wire.NewTxIn(&contractOutPoint, nil, nil))\n\tredeemTx.AddTxOut(wire.NewTxOut(0, outScript)) // amount set below\n\tredeemSize := util.EstimateRedeemSerializeSize(contract, redeemTx.TxOut)\n\tfee := txrules.FeeForSerializeSize(feePerKb, redeemSize)\n\tredeemTx.TxOut[0].Value = contractTx.TxOut[contractOut].Value - int64(fee)\n\tif txrules.IsDustOutput(redeemTx.TxOut[0], minFeePerKb) {\n\t\tpanic(fmt.Errorf(\"redeem output value of %v is dust\", diviutil.Amount(redeemTx.TxOut[0].Value)))\n\t}\n\n\tredeemSig, redeemPubKey, err := CreateSig(redeemTx, 0, contract, recipientAddr, client)\n\tif err != nil {\n\t\treturn api.RedeemResponse{\"\", \"\", struct{}{}, nil, 51200}, err\n\t}\n\tredeemSigScript, err := RedeemP2SHContract(contract, redeemSig, redeemPubKey, secret)\n\tif err != nil {\n\t\treturn api.RedeemResponse{\"\", \"\", struct{}{}, nil, 51200}, err\n\t}\n\tredeemTx.TxIn[0].SignatureScript = redeemSigScript\n\n\tredeemTxHash := redeemTx.TxHash()\n\tredeemFeePerKb := CalcFeePerKb(fee, redeemTx.SerializeSize())\n\n\tvar buf bytes.Buffer\n\tbuf.Grow(redeemTx.SerializeSize())\n\tredeemTx.Serialize(&buf)\n\n\tif autopublish == false {\n\t\tfmt.Printf(\"Redeem fee: %v (%0.8f BTC/kB)\\n\\n\", fee, redeemFeePerKb)\n\t\tfmt.Printf(\"Redeem transaction (%v):\\n\", &redeemTxHash)\n\t\tfmt.Printf(\"%x\\n\\n\", buf.Bytes())\n\t}\n\n\tif util.Verify {\n\t\te, err := txscript.NewEngine(contractTx.TxOut[contractOutPoint.Index].PkScript,\n\t\t\tredeemTx, 0, txscript.StandardVerifyFlags, txscript.NewSigCache(10),\n\t\t\ttxscript.NewTxSigHashes(redeemTx), contractTx.TxOut[contractOut].Value)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\terr = e.Execute()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tPromptPublishTx(client, redeemTx, \"redeem\", autopublish)\n\n\treturn api.RedeemResponse{\n\t\tfee.String(),\n\t\tredeemTxHash.String(),\n\t\tstruct{}{},\n\t\tnil,\n\t\t51200,\n\t}, nil\n}", "func (k Keeper) ClaimHardReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tk.SynchronizeHardLiquidityProviderClaim(ctx, owner)\n\n\tsyncedClaim, found := k.GetHardLiquidityProviderClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr := k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetHardLiquidityProviderClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func (_Ethdkg *EthdkgTransactorSession) SubmitDispute(issuer common.Address, issuer_list_idx *big.Int, disputer_list_idx *big.Int, encrypted_shares []*big.Int, commitments [][2]*big.Int, shared_key [2]*big.Int, shared_key_correctness_proof [2]*big.Int) (*types.Transaction, error) {\n\treturn _Ethdkg.Contract.SubmitDispute(&_Ethdkg.TransactOpts, issuer, issuer_list_idx, disputer_list_idx, encrypted_shares, commitments, shared_key, shared_key_correctness_proof)\n}", "func PostHandleMsgStakeUpdate(ctx sdk.Context, k keeper.Keeper, msg types.MsgStakeUpdate, sideTxResult tmprototypes.SideTxResultType) (*sdk.Result, error) {\n\t// Skip handler if stakeUpdate is not approved\n\tif sideTxResult != tmprototypes.SideTxResultType_YES {\n\t\tk.Logger(ctx).Debug(\"Skipping stake update since side-tx didn't get yes votes\")\n\t\treturn nil, hmCommon.ErrSideTxValidation\n\t}\n\n\t// Check for replay attack\n\tblockNumber := new(big.Int).SetUint64(msg.BlockNumber)\n\tsequence := new(big.Int).Mul(blockNumber, big.NewInt(hmTypes.DefaultLogIndexUnit))\n\tsequence.Add(sequence, new(big.Int).SetUint64(msg.LogIndex))\n\n\t// check if incoming tx is older\n\tif k.HasStakingSequence(ctx, sequence.String()) {\n\t\tk.Logger(ctx).Error(\"Older invalid tx found\")\n\t\treturn nil, hmCommon.ErrOldTx\n\t}\n\n\tk.Logger(ctx).Debug(\"Updating validator stake\", \"sideTxResult\", sideTxResult)\n\n\t// pull validator from store\n\tvalidator, ok := k.GetValidatorFromValID(ctx, msg.ID)\n\tif !ok {\n\t\tk.Logger(ctx).Error(\"Fetching of validator from store failed\", \"validatorId\", msg.ID)\n\t\treturn nil, hmCommon.ErrNoValidator\n\t}\n\n\t// update last updated\n\tvalidator.LastUpdated = sequence.String()\n\n\t// update nonce\n\tvalidator.Nonce = msg.Nonce\n\n\t// set validator amount\n\tp, err := helper.GetPowerFromAmount(msg.NewAmount.BigInt())\n\tif err != nil {\n\t\treturn nil, hmCommon.ErrInvalidMsg\n\t}\n\tvalidator.VotingPower = p.Int64()\n\n\t// save validator\n\terr = k.AddValidator(ctx, validator)\n\tif err != nil {\n\t\tk.Logger(ctx).Error(\"Unable to update signer\", \"error\", err, \"ValidatorID\", validator.ID)\n\t\treturn nil, hmCommon.ErrSignerUpdateError\n\t}\n\n\t// save staking sequence\n\tk.SetStakingSequence(ctx, sequence.String())\n\n\t// TX bytes\n\ttxBytes := ctx.TxBytes()\n\thash := tmTypes.Tx(txBytes).Hash()\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeStakeUpdate,\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAction, msg.Type()),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory),\n\t\t\tsdk.NewAttribute(hmTypes.AttributeKeyTxHash, hmCommonTypes.BytesToHeimdallHash(hash).Hex()), // tx hash\n\t\t\tsdk.NewAttribute(hmTypes.AttributeKeySideTxResult, sideTxResult.String()), // result\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidatorID, strconv.FormatUint(validator.ID.Uint64(), 10)),\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidatorNonce, strconv.FormatUint(msg.Nonce, 10)),\n\t\t),\n\t})\n\n\treturn &sdk.Result{\n\t\tEvents: ctx.EventManager().ABCIEvents(),\n\t}, nil\n}", "func (node *TreeNode) backpropagateReward(scores [2]float64) {\n\tcurrentNode := node\n\tfor currentNode.Parent != nil {\n\t\tcurrentNode.VisitCount += 1.0\n\t\tcurrentNode.CumulativeScore[0] += scores[0]\n\t\tcurrentNode.CumulativeScore[1] += scores[1]\n\t\tcurrentNode = currentNode.Parent\n\t}\n\t//Increment root node counter\n\tcurrentNode.VisitCount += 1.0\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactor) DistributeERC20Reward(opts *bind.TransactOpts, _tokenAddress common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.contract.Transact(opts, \"distributeERC20Reward\", _tokenAddress, _value)\n}", "func (c *Calculator) votingReward(\n\tmultiplier *big.Int,\n\tdivider *big.Int,\n\tfrom int,\n\tto int,\n\tprepInfo map[string]*pRepEnable,\n\titer icstate.VotingIterator,\n) *big.Int {\n\ttotal := new(big.Int)\n\tcheckMinVoting := c.global.GetIISSVersion() == icstate.IISSVersion2\n\tfor ; iter.Has(); iter.Next() {\n\t\tif voting, err := iter.Get(); err != nil {\n\t\t\tc.log.Errorf(\"Failed to iterate votings err=%+v\", err)\n\t\t} else {\n\t\t\tif checkMinVoting && voting.Amount().Cmp(BigIntMinDelegation) < 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ts := from\n\t\t\te := to\n\t\t\tif prep, ok := prepInfo[icutils.ToKey(voting.To())]; ok {\n\t\t\t\tif prep.StartOffset() != 0 && prep.StartOffset() > s {\n\t\t\t\t\ts = prep.StartOffset()\n\t\t\t\t}\n\t\t\t\tif prep.EndOffset() != 0 && prep.EndOffset() < e {\n\t\t\t\t\te = prep.EndOffset()\n\t\t\t\t}\n\t\t\t\tperiod := e - s\n\t\t\t\tif period <= 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\treward := new(big.Int).Mul(multiplier, voting.Amount())\n\t\t\t\treward.Mul(reward, big.NewInt(int64(period)))\n\t\t\t\treward.Div(reward, divider)\n\t\t\t\ttotal.Add(total, reward)\n\t\t\t\tc.log.Tracef(\"VotingReward %s: %s = %s * %s * %d / %s\",\n\t\t\t\t\tvoting.To(), reward, multiplier, voting.Amount(), period, divider)\n\t\t\t}\n\t\t}\n\t}\n\treturn total\n}", "func (dcr *ExchangeWallet) Redeem(redemptions []*asset.Redemption) ([]dex.Bytes, asset.Coin, uint64, error) {\n\t// Create a transaction that spends the referenced contract.\n\tmsgTx := wire.NewMsgTx()\n\tvar totalIn uint64\n\tvar contracts [][]byte\n\tvar addresses []dcrutil.Address\n\tfor _, r := range redemptions {\n\t\tcinfo, ok := r.Spends.(*auditInfo)\n\t\tif !ok {\n\t\t\treturn nil, nil, 0, fmt.Errorf(\"Redemption contract info of wrong type\")\n\t\t}\n\t\t// Extract the swap contract recipient and secret hash and check the secret\n\t\t// hash against the hash of the provided secret.\n\t\tcontract := r.Spends.Contract()\n\t\t_, receiver, _, secretHash, err := dexdcr.ExtractSwapDetails(contract, chainParams)\n\t\tif err != nil {\n\t\t\treturn nil, nil, 0, fmt.Errorf(\"error extracting swap addresses: %w\", err)\n\t\t}\n\t\tcheckSecretHash := sha256.Sum256(r.Secret)\n\t\tif !bytes.Equal(checkSecretHash[:], secretHash) {\n\t\t\treturn nil, nil, 0, fmt.Errorf(\"secret hash mismatch. %x != %x\", checkSecretHash[:], secretHash)\n\t\t}\n\t\taddresses = append(addresses, receiver)\n\t\tcontracts = append(contracts, contract)\n\t\tprevOut := cinfo.output.wireOutPoint()\n\t\ttxIn := wire.NewTxIn(prevOut, int64(cinfo.output.value), []byte{})\n\t\t// Sequence = 0xffffffff - 1 is special value that marks the transaction as\n\t\t// irreplaceable and enables the use of lock time.\n\t\t//\n\t\t// https://github.com/bitcoin/bips/blob/master/bip-0125.mediawiki#Spending_wallet_policy\n\t\ttxIn.Sequence = wire.MaxTxInSequenceNum - 1\n\t\tmsgTx.AddTxIn(txIn)\n\t\ttotalIn += cinfo.output.value\n\t}\n\n\t// Calculate the size and the fees.\n\tsize := msgTx.SerializeSize() + dexdcr.RedeemSwapSigScriptSize*len(redemptions) + dexdcr.P2PKHOutputSize\n\tfeeRate := dcr.feeRateWithFallback(dcr.redeemConfTarget)\n\tfee := feeRate * uint64(size)\n\tif fee > totalIn {\n\t\treturn nil, nil, 0, fmt.Errorf(\"redeem tx not worth the fees\")\n\t}\n\t// Send the funds back to the exchange wallet.\n\ttxOut, _, err := dcr.makeChangeOut(totalIn - fee)\n\tif err != nil {\n\t\treturn nil, nil, 0, err\n\t}\n\t// One last check for dust.\n\tif dexdcr.IsDust(txOut, feeRate) {\n\t\treturn nil, nil, 0, fmt.Errorf(\"redeem output is dust\")\n\t}\n\tmsgTx.AddTxOut(txOut)\n\t// Sign the inputs.\n\tfor i, r := range redemptions {\n\t\tcontract := contracts[i]\n\t\tredeemSig, redeemPubKey, err := dcr.createSig(msgTx, i, contract, addresses[i])\n\t\tif err != nil {\n\t\t\treturn nil, nil, 0, err\n\t\t}\n\t\tredeemSigScript, err := dexdcr.RedeemP2SHContract(contract, redeemSig, redeemPubKey, r.Secret)\n\t\tif err != nil {\n\t\t\treturn nil, nil, 0, err\n\t\t}\n\t\tmsgTx.TxIn[i].SignatureScript = redeemSigScript\n\t}\n\t// Send the transaction.\n\tcheckHash := msgTx.TxHash()\n\ttxHash, err := dcr.node.SendRawTransaction(dcr.ctx, msgTx, false)\n\tif err != nil {\n\t\treturn nil, nil, 0, translateRPCCancelErr(err)\n\t}\n\tif *txHash != checkHash {\n\t\treturn nil, nil, 0, fmt.Errorf(\"redemption sent, but received unexpected transaction ID back from RPC server. \"+\n\t\t\t\"expected %s, got %s\", *txHash, checkHash)\n\t}\n\tcoinIDs := make([]dex.Bytes, 0, len(redemptions))\n\tfor i := range redemptions {\n\t\tcoinIDs = append(coinIDs, toCoinID(txHash, uint32(i)))\n\t}\n\n\treturn coinIDs, newOutput(txHash, 0, uint64(txOut.Value), wire.TxTreeRegular), fee, nil\n}", "func (s *MutableState) AddRewards(time epochtime.EpochTime, factor *quantity.Quantity, accounts []signature.PublicKey) error {\n\tsteps, err := s.RewardSchedule()\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar activeStep *staking.RewardStep\n\tfor _, step := range steps {\n\t\tif time < step.Until {\n\t\t\tactiveStep = &step\n\t\t\tbreak\n\t\t}\n\t}\n\tif activeStep == nil {\n\t\t// We're past the end of the schedule.\n\t\treturn nil\n\t}\n\n\tcommonPool, err := s.CommonPool()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"loading common pool\")\n\t}\n\n\tfor _, id := range accounts {\n\t\tent := s.Account(id)\n\n\t\tq := ent.Escrow.Active.Balance.Clone()\n\t\t// Multiply first.\n\t\tif err := q.Mul(factor); err != nil {\n\t\t\treturn errors.Wrap(err, \"multiplying by reward factor\")\n\t\t}\n\t\tif err := q.Mul(&activeStep.Scale); err != nil {\n\t\t\treturn errors.Wrap(err, \"multiplying by reward step scale\")\n\t\t}\n\t\tif err := q.Quo(staking.RewardAmountDenominator); err != nil {\n\t\t\treturn errors.Wrap(err, \"dividing by reward amount denominator\")\n\t\t}\n\n\t\tif q.IsZero() {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar com *quantity.Quantity\n\t\trate := ent.Escrow.CommissionSchedule.CurrentRate(time)\n\t\tif rate != nil {\n\t\t\tcom = q.Clone()\n\t\t\t// Multiply first.\n\t\t\tif err := com.Mul(rate); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"multiplying by commission rate\")\n\t\t\t}\n\t\t\tif err := com.Quo(staking.CommissionRateDenominator); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"dividing by commission rate denominator\")\n\t\t\t}\n\n\t\t\tif err := q.Sub(com); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"subtracting commission\")\n\t\t\t}\n\t\t}\n\n\t\tif !q.IsZero() {\n\t\t\tif err := quantity.Move(&ent.Escrow.Active.Balance, commonPool, q); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"transferring to active escrow balance from common pool\")\n\t\t\t}\n\t\t}\n\n\t\tif com != nil && !com.IsZero() {\n\t\t\tdelegation := s.Delegation(id, id)\n\n\t\t\tif err := ent.Escrow.Active.Deposit(&delegation.Shares, commonPool, com); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"depositing commission\")\n\t\t\t}\n\n\t\t\ts.SetDelegation(id, id, delegation)\n\t\t}\n\n\t\ts.SetAccount(id, ent)\n\t}\n\n\ts.SetCommonPool(commonPool)\n\n\treturn nil\n}", "func (t *trusteeImpl) NewMiningRewardTx(block consensus.Block) *consensus.Transaction {\n\tvar tx *consensus.Transaction\n\t// build list of miner nodes for uncle blocks\n\tuncleMiners := make([][]byte, len(block.UncleMiners()))\n\tfor i, uncleMiner := range block.UncleMiners() {\n\t\tuncleMiners[i] = uncleMiner\n\t}\n\t\n\tops := make([]Op, 1 + len(uncleMiners))\n\t// first add self's mining reward\n\tops[0] = *t.myReward\n\t\n\t// now add award for each uncle\n\tfor i, uncleMiner := range uncleMiners {\n\t\top := NewOp(OpReward)\n\t\top.Params[ParamUncle] = bytesToHexString(uncleMiner)\n\t\top.Params[ParamAward] = UncleAward\n\t\tops[i+1] = *op \n\t}\n\t// serialize ops into payload\n\tif payload,err := common.Serialize(ops); err != nil {\n\t\tt.log.Error(\"Failed to serialize ops into payload: %s\", err)\n\t\treturn nil\n\t} else {\n\t\t// make a signed transaction out of payload\n\t\tif signature := t.sign(payload); len(signature) > 0 {\n\t\t\t// return the signed transaction\n\t\t\ttx = consensus.NewTransaction(payload, signature, t.myAddress)\n\t\t\tblock.AddTransaction(tx)\n\t\t\tt.process(block, tx)\n\t\t}\n\t}\n\treturn tx\n}", "func sendMsgEditPost(\n\tr *rand.Rand, app *baseapp.BaseApp, ak auth.AccountKeeper,\n\tmsg types.MsgEditPost, ctx sdk.Context, chainID string, privkeys []crypto.PrivKey,\n) error {\n\n\taccount := ak.GetAccount(ctx, msg.Editor)\n\tcoins := account.SpendableCoins(ctx.BlockTime())\n\n\tfees, err := sim.RandomFees(r, ctx, coins)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttx := helpers.GenTx(\n\t\t[]sdk.Msg{msg},\n\t\tfees,\n\t\tDefaultGasValue,\n\t\tchainID,\n\t\t[]uint64{account.GetAccountNumber()},\n\t\t[]uint64{account.GetSequence()},\n\t\tprivkeys...,\n\t)\n\n\t_, _, err = app.Deliver(tx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func redeem (stub shim.ChaincodeStubInterface, args []string) ([]byte,error){\n\n\tif len(args) != 5 {\n\t\t\tfmt.Println(\" Incorrect number of arguments sent to redeem. Expecting 5. Received \" + strconv.Itoa(len(args)))\n\t\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting 5\")\n\t\t}\n\n\t\t_, err := LoyaltyPkg.RedeemPoints(stub, args)\n\n\tif err != nil {\n\n\t\tfmt.Println(err)\n\t\treturn nil, errors.New(\"Errors while creating wallet for user \" + args[0])\n\t}\n\n\tlogger.Info(\"Successfully redeemed points for user \" + args[0])\n\n\treturn nil, nil\n\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 PostVault(c *gin.Context) {\n\tdbmap := c.MustGet(\"DBmap\").(*gorp.DbMap)\n\tverbose := c.MustGet(\"Verbose\").(bool)\n\n\tvar vault Vault\n\tc.Bind(&vault)\n\n\tif verbose == true {\n\t\tfmt.Println(vault)\n\t\tfmt.Println(len(vault.VaultName))\n\t}\n\n\tif len(vault.VaultName) >= 3 { // XXX Check mandatory fields\n\t\terr := dbmap.Insert(&vault)\n\t\tif err == nil {\n\t\t\tc.JSON(201, vault)\n\t\t} else {\n\t\t\tcheckErr(err, \"Insert failed\")\n\t\t}\n\n\t} else {\n\t\tc.JSON(400, gin.H{\"error\": \"Mandatory fields are empty\"})\n\t}\n\n\t// curl -i -X POST -H \"Content-Type: application/json\" -d \"{ \\\"firstname\\\": \\\"Thea\\\", \\\"lastname\\\": \\\"Queen\\\" }\" http://localhost:8080/api/v1/vaults\n}", "func (d *Dao) AddReward(c context.Context, iRewardID int64, uid int64, iSource int64, iRoomid int64, iLifespan int64) (err error) {\n\t//aReward, _ := getRewardConfByLid(iRewardID)\n\n\tm, _ := time.ParseDuration(fmt.Sprintf(\"+%dh\", iLifespan))\n\n\targ := &AnchorTaskModel.AnchorReward{\n\t\tUid: uid,\n\t\tRewardId: iRewardID,\n\t\tRoomid: iRoomid,\n\t\tSource: iSource,\n\t\tAchieveTime: xtime.Time(time.Now().Unix()),\n\t\tExpireTime: xtime.Time(time.Now().Add(m).Unix()),\n\t\tStatus: model.RewardUnUsed,\n\t}\n\n\t//spew.Dump\n\t// (arg)\n\tif err := d.orm.Create(arg).Error; err != nil {\n\t\tlog.Error(\"addReward(%v) error(%v)\", arg, err)\n\t\treturn err\n\t}\n\n\tif err := d.SetNewReward(c, uid, int64(1)); err != nil {\n\t\tlog.Error(\"addRewardMc(%v) error(%v)\", uid, err)\n\t}\n\n\tif err := d.SetHasReward(c, uid, int64(1)); err != nil {\n\t\tlog.Error(\"SetHasReward(%v) error(%v)\", uid, err)\n\t}\n\n\tlog.Info(\"addReward (%v) succ\", arg)\n\n\treturn\n}", "func (n *Notary) PostPersist() {\n\tacc := n.getAccount()\n\tif acc == nil {\n\t\treturn\n\t}\n\n\tn.reqMtx.Lock()\n\tdefer n.reqMtx.Unlock()\n\tcurrHeight := n.Config.Chain.BlockHeight()\n\tfor h, r := range n.requests {\n\t\tif !r.isSent && r.isMainCompleted() && r.minNotValidBefore > currHeight {\n\t\t\tif err := n.finalize(acc, r.main, h); err != nil {\n\t\t\t\tn.Config.Log.Error(\"failed to finalize main transaction\", zap.Error(err))\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif r.minNotValidBefore <= currHeight { // then at least one of the fallbacks can already be sent.\n\t\t\tfor _, fb := range r.fallbacks {\n\t\t\t\tif nvb := fb.GetAttributes(transaction.NotValidBeforeT)[0].Value.(*transaction.NotValidBefore).Height; nvb <= currHeight {\n\t\t\t\t\t// Ignore the error, wait for the next block to resend them\n\t\t\t\t\t_ = n.finalize(acc, fb, h)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (dcr *ExchangeWallet) Redeem(form *asset.RedeemForm) ([]dex.Bytes, asset.Coin, uint64, error) {\n\t// Create a transaction that spends the referenced contract.\n\tmsgTx := wire.NewMsgTx()\n\tvar totalIn uint64\n\tvar contracts [][]byte\n\tvar addresses []stdaddr.Address\n\tfor _, r := range form.Redemptions {\n\t\tif r.Spends == nil {\n\t\t\treturn nil, nil, 0, fmt.Errorf(\"no audit info\")\n\t\t}\n\n\t\tcinfo, err := convertAuditInfo(r.Spends, dcr.chainParams)\n\t\tif err != nil {\n\t\t\treturn nil, nil, 0, err\n\t\t}\n\n\t\t// Extract the swap contract recipient and secret hash and check the secret\n\t\t// hash against the hash of the provided secret.\n\t\tcontract := cinfo.contract\n\t\t_, receiver, _, secretHash, err := dexdcr.ExtractSwapDetails(contract, dcr.chainParams)\n\t\tif err != nil {\n\t\t\treturn nil, nil, 0, fmt.Errorf(\"error extracting swap addresses: %w\", err)\n\t\t}\n\t\tcheckSecretHash := sha256.Sum256(r.Secret)\n\t\tif !bytes.Equal(checkSecretHash[:], secretHash) {\n\t\t\treturn nil, nil, 0, fmt.Errorf(\"secret hash mismatch. %x != %x\", checkSecretHash[:], secretHash)\n\t\t}\n\t\taddresses = append(addresses, receiver)\n\t\tcontracts = append(contracts, contract)\n\t\tprevOut := cinfo.output.wireOutPoint()\n\t\ttxIn := wire.NewTxIn(prevOut, int64(cinfo.output.value), []byte{})\n\t\tmsgTx.AddTxIn(txIn)\n\t\ttotalIn += cinfo.output.value\n\t}\n\n\t// Calculate the size and the fees.\n\tsize := msgTx.SerializeSize() + dexdcr.RedeemSwapSigScriptSize*len(form.Redemptions) + dexdcr.P2PKHOutputSize\n\n\tcustomCfg := new(redeemOptions)\n\terr := config.Unmapify(form.Options, customCfg)\n\tif err != nil {\n\t\treturn nil, nil, 0, fmt.Errorf(\"error parsing selected swap options: %w\", err)\n\t}\n\n\trawFeeRate := dcr.targetFeeRateWithFallback(dcr.redeemConfTarget, form.FeeSuggestion)\n\tfeeRate, err := calcBumpedRate(rawFeeRate, customCfg.FeeBump)\n\tif err != nil {\n\t\tdcr.log.Errorf(\"calcBumpRate error: %v\", err)\n\t}\n\tfee := feeRate * uint64(size)\n\tif fee > totalIn {\n\t\t// Double check that the fee bump isn't the issue.\n\t\tfeeRate = rawFeeRate\n\t\tfee = feeRate * uint64(size)\n\t\tif fee > totalIn {\n\t\t\treturn nil, nil, 0, fmt.Errorf(\"redeem tx not worth the fees\")\n\t\t}\n\t\tdcr.log.Warnf(\"Ignoring fee bump (%v) resulting in fees > redemption\", float64PtrStr(customCfg.FeeBump))\n\t}\n\n\t// Send the funds back to the exchange wallet.\n\ttxOut, _, err := dcr.makeChangeOut(dcr.depositAccount(), totalIn-fee)\n\tif err != nil {\n\t\treturn nil, nil, 0, err\n\t}\n\t// One last check for dust.\n\tif dexdcr.IsDust(txOut, feeRate) {\n\t\treturn nil, nil, 0, fmt.Errorf(\"redeem output is dust\")\n\t}\n\tmsgTx.AddTxOut(txOut)\n\t// Sign the inputs.\n\tfor i, r := range form.Redemptions {\n\t\tcontract := contracts[i]\n\t\tredeemSig, redeemPubKey, err := dcr.createSig(msgTx, i, contract, addresses[i])\n\t\tif err != nil {\n\t\t\treturn nil, nil, 0, err\n\t\t}\n\t\tredeemSigScript, err := dexdcr.RedeemP2SHContract(contract, redeemSig, redeemPubKey, r.Secret)\n\t\tif err != nil {\n\t\t\treturn nil, nil, 0, err\n\t\t}\n\t\tmsgTx.TxIn[i].SignatureScript = redeemSigScript\n\t}\n\t// Send the transaction.\n\tcheckHash := msgTx.TxHash()\n\ttxHash, err := dcr.wallet.SendRawTransaction(dcr.ctx, msgTx, false)\n\tif err != nil {\n\t\treturn nil, nil, 0, err\n\t}\n\tif *txHash != checkHash {\n\t\treturn nil, nil, 0, fmt.Errorf(\"redemption sent, but received unexpected transaction ID back from RPC server. \"+\n\t\t\t\"expected %s, got %s\", *txHash, checkHash)\n\t}\n\tcoinIDs := make([]dex.Bytes, 0, len(form.Redemptions))\n\tfor i := range form.Redemptions {\n\t\tcoinIDs = append(coinIDs, toCoinID(txHash, uint32(i)))\n\t}\n\n\treturn coinIDs, newOutput(txHash, 0, uint64(txOut.Value), wire.TxTreeRegular), fee, nil\n}", "func (c *Client) RenterPostRateLimit(readBPS, writeBPS int64) (err error) {\n\tvalues := url.Values{}\n\tvalues.Set(\"maxdownloadspeed\", strconv.FormatInt(readBPS, 10))\n\tvalues.Set(\"maxuploadspeed\", strconv.FormatInt(writeBPS, 10))\n\terr = c.post(\"/renter\", values.Encode(), nil)\n\treturn\n}", "func (btc *ExchangeWallet) Redeem(redemptions []*asset.Redemption) ([]dex.Bytes, asset.Coin, error) {\n\t// Create a transaction that spends the referenced contract.\n\tmsgTx := wire.NewMsgTx(wire.TxVersion)\n\tvar totalIn uint64\n\tvar contracts [][]byte\n\tvar addresses []btcutil.Address\n\tfor _, r := range redemptions {\n\t\tcinfo, ok := r.Spends.(*auditInfo)\n\t\tif !ok {\n\t\t\treturn nil, nil, fmt.Errorf(\"Redemption contract info of wrong type\")\n\t\t}\n\t\t// Extract the swap contract recipient and secret hash and check the secret\n\t\t// hash against the hash of the provided secret.\n\t\t_, receiver, _, secretHash, err := dexbtc.ExtractSwapDetails(cinfo.output.redeem, btc.chainParams)\n\t\tif err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"error extracting swap addresses: %v\", err)\n\t\t}\n\t\tcheckSecretHash := sha256.Sum256(r.Secret)\n\t\tif !bytes.Equal(checkSecretHash[:], secretHash) {\n\t\t\treturn nil, nil, fmt.Errorf(\"secret hash mismatch\")\n\t\t}\n\t\taddresses = append(addresses, receiver)\n\t\tcontracts = append(contracts, cinfo.output.redeem)\n\t\tprevOut := wire.NewOutPoint(&cinfo.output.txHash, cinfo.output.vout)\n\t\ttxIn := wire.NewTxIn(prevOut, []byte{}, nil)\n\t\t// Enable locktime\n\t\t// https://github.com/bitcoin/bips/blob/master/bip-0125.mediawiki#Spending_wallet_policy\n\t\ttxIn.Sequence = wire.MaxTxInSequenceNum - 1\n\t\tmsgTx.AddTxIn(txIn)\n\t\ttotalIn += cinfo.output.value\n\t}\n\n\t// Calculate the size and the fees.\n\tsize := msgTx.SerializeSize() + dexbtc.RedeemSwapSigScriptSize*len(redemptions) + dexbtc.P2WPKHOutputSize\n\tfeeRate := btc.feeRateWithFallback()\n\tfee := feeRate * uint64(size)\n\tif fee > totalIn {\n\t\treturn nil, nil, fmt.Errorf(\"redeem tx not worth the fees\")\n\t}\n\t// Send the funds back to the exchange wallet.\n\tredeemAddr, err := btc.wallet.ChangeAddress()\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"error getting new address from the wallet: %v\", err)\n\t}\n\tpkScript, err := txscript.PayToAddrScript(redeemAddr)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"error creating change script: %v\", err)\n\t}\n\ttxOut := wire.NewTxOut(int64(totalIn-fee), pkScript)\n\t// One last check for dust.\n\tif dexbtc.IsDust(txOut, feeRate) {\n\t\treturn nil, nil, fmt.Errorf(\"redeem output is dust\")\n\t}\n\tmsgTx.AddTxOut(txOut)\n\t// Sign the inputs.\n\tfor i, r := range redemptions {\n\t\tcontract := contracts[i]\n\t\tredeemSig, redeemPubKey, err := btc.createSig(msgTx, i, contract, addresses[i])\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tredeemSigScript, err := dexbtc.RedeemP2SHContract(contract, redeemSig, redeemPubKey, r.Secret)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tmsgTx.TxIn[i].SignatureScript = redeemSigScript\n\t}\n\t// Send the transaction.\n\tcheckHash := msgTx.TxHash()\n\ttxHash, err := btc.node.SendRawTransaction(msgTx, false)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif *txHash != checkHash {\n\t\treturn nil, nil, fmt.Errorf(\"redemption sent, but received unexpected transaction ID back from RPC server. \"+\n\t\t\t\"expected %s, got %s\", *txHash, checkHash)\n\t}\n\t// Log the change output.\n\tbtc.addChange(txHash.String(), 0)\n\tcoinIDs := make([]dex.Bytes, 0, len(redemptions))\n\tfor i := range redemptions {\n\t\tcoinIDs = append(coinIDs, toCoinID(txHash, uint32(i)))\n\t}\n\treturn coinIDs, newOutput(btc.node, txHash, 0, uint64(txOut.Value), nil), nil\n}", "func (_XStaking *XStakingCaller) Rewards(opts *bind.CallOpts, arg0 common.Address) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _XStaking.contract.Call(opts, &out, \"rewards\", arg0)\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 PostTimeAdjustment(\n\telapseTime int64, paras *param.EvaluateOfContentValueParam) float64 {\n\treturn (1.0 / (1.0 + math.Exp(\n\t\t(float64(elapseTime)/float64(paras.ConsumptionTimeAdjustBase) -\n\t\t\tfloat64(paras.ConsumptionTimeAdjustOffset)))))\n}", "func (_Smartchef *SmartchefCaller) RewardPerBlock(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Smartchef.contract.Call(opts, out, \"rewardPerBlock\")\n\treturn *ret0, err\n}", "func (k Keeper) ClaimDelegatorReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tclaim, found := k.GetDelegatorClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tsyncedClaim, err := k.SynchronizeDelegatorClaim(ctx, claim)\n\tif err != nil {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr = k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetDelegatorClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn 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 (_Token *TokenCallerSession) BaseReward(index *big.Int) (*big.Int, *big.Int, *big.Int, error) {\n\treturn _Token.Contract.BaseReward(&_Token.CallOpts, index)\n}", "func (_Token *TokenSession) BaseReward(index *big.Int) (*big.Int, *big.Int, *big.Int, error) {\n\treturn _Token.Contract.BaseReward(&_Token.CallOpts, index)\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactorSession) DistributeERC20Reward(_tokenAddress common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.DistributeERC20Reward(&_BondedECDSAKeep.TransactOpts, _tokenAddress, _value)\n}", "func (_BondedECDSAKeep *BondedECDSAKeepSession) DistributeERC20Reward(_tokenAddress common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.DistributeERC20Reward(&_BondedECDSAKeep.TransactOpts, _tokenAddress, _value)\n}", "func (_Univ2 *Univ2Transactor) Permit(opts *bind.TransactOpts, owner common.Address, spender common.Address, value *big.Int, deadline *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) {\n\treturn _Univ2.contract.Transact(opts, \"permit\", owner, spender, value, deadline, v, r, s)\n}", "func (d *Dao) UseReward(id int64, usePlat string) (rst bool, err error) {\n\tif err := d.orm.\n\t\tModel(&model.AnchorReward{}).\n\t\tWhere(\"id=?\", id).\n\t\tUpdate(map[string]interface{}{\"status\": model.RewardUsed, \"use_plat\": usePlat, \"use_time\": xtime.Time(time.Now().Unix())}).Error; err != nil {\n\t\tlog.Error(\"useReward (%v) error(%v)\", id, err)\n\t\treturn rst, err\n\t}\n\trst = true\n\treturn\n}", "func (_Contract *ContractCaller) TaskErasingReward(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Contract.contract.Call(opts, &out, \"taskErasingReward\")\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 (m *Mantle) replenishBalance(w *botWallet) {\n\t// Get the Balance from the user in case it changed while while this note\n\t// was in the notification pipeline.\n\tbal, err := m.AssetBalance(w.assetID)\n\tif err != nil {\n\t\tm.fatalError(\"error updating %s balance: %v\", w.symbol, err)\n\t\treturn\n\t}\n\n\tm.log.Debugf(\"Balance note received for %s (minFunds = %s, maxFunds = %s): %s\",\n\t\tw.symbol, valString(w.minFunds), valString(w.maxFunds), mustJSON(bal))\n\n\teffectiveMax := w.maxFunds + (w.maxFunds - w.minFunds)\n\n\tif bal.Available < w.minFunds {\n\t\tchunk := (w.maxFunds - bal.Available) / uint64(w.numCoins)\n\t\tfor i := 0; i < w.numCoins; i++ {\n\t\t\tm.log.Debugf(\"Requesting %s from %s alpha node\", valString(chunk), w.symbol)\n\t\t\tcmdOut := <-harnessCtl(w.symbol, \"./alpha\", \"sendtoaddress\", w.address, valString(chunk))\n\t\t\tif cmdOut.err != nil {\n\t\t\t\tm.fatalError(\"error refreshing balance for %s: %v\", w.symbol, cmdOut.err)\n\t\t\t}\n\t\t}\n\t} else if bal.Available > effectiveMax {\n\t\t// Send some back to the alpha address.\n\t\tamt := bal.Available - w.maxFunds\n\t\tm.log.Debugf(\"Sending %s back to %s alpha node\", valString(amt), w.symbol)\n\t\t_, err := m.Withdraw(pass, w.assetID, amt, returnAddress(w.symbol, alpha))\n\t\tif err != nil {\n\t\t\tm.fatalError(\"failed to withdraw funds to alpha: %v\", err)\n\t\t}\n\t}\n}", "func payout(delegate string, operator string) string {\n\t// get operator's address\n\toperator_addr, err := alias.Address(operator)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// get delegate's name to 12-byte array\n\tdelegate_name := delegateName(delegate)\n\n\trs := calculateRewardShares(operator_addr, delegate_name, epochToQuery)\n\n\t// prepare input for multisend\n\t// https://member.iotex.io/multi-send\n\tvar voters []string\n\tvar rewards []string\n\n\tstradd := func(a string, b string, c string) string {\n\t\taa, _ := new(big.Int).SetString(a, 10)\n\t\tbb, _ := new(big.Int).SetString(b, 10)\n\t\tcc, _ := new(big.Int).SetString(c, 10)\n\t\treturn cc.Add(aa.Add(aa, bb), cc).Text(10)\n\t}\n\n\tfor _, share := range rs.Shares {\n\t\tvoters = append(voters, \"0x\" + share.ETHAddr)\n\t\trewards = append(rewards, stradd(\n\t\t\t\t\t\tshare.Reward.Block,\n\t\t\t\t\t\tshare.Reward.FoundationBonus,\n\t\t\t\t\t\tshare.Reward.EpochBonus))\n\t}\n\n\tvar sent []MultisendReward\n\tfor i, a := range rewards {\n\t\tamount, _ := new(big.Int).SetString(a, 10)\n\t\tsent = append(sent, MultisendReward{voters[i],\n\t\t\t\t\tutil.RauToString(amount, util.IotxDecimalNum)})\n\t}\n\ts, _ := json.Marshal(sent)\n\tfmt.Println(string(s))\n\n\treturn rs.String()\n}", "func (c *Contract) Payback(ctx TransactionContextInterface, jeweler string, paperNumber string, paidbackDateTime string) (*InventoryFinancingPaper, error) {\r\n\tpaper, err := ctx.GetPaperList().GetPaper(jeweler, paperNumber)\r\n\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\tif paper.IsPaidBack() {\r\n\t\treturn nil, fmt.Errorf(\"paper %s:%s is already PaidBack\", jeweler, paperNumber)\r\n\t}\r\n\r\n\tpaper.SetPaidBack()\r\n\r\n\terr = ctx.GetPaperList().UpdatePaper(paper)\r\n\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\tfmt.Printf(\"inventory paper %q:%q is paid back by %q,The paidback date is %q. Current state = %q\", jeweler, paperNumber, jeweler, paidbackDateTime, paper.GetState())\r\n\treturn paper, nil\r\n}", "func sendMsgAddPostReaction(\n\tr *rand.Rand, app *baseapp.BaseApp, ak authkeeper.AccountKeeper, bk bankkeeper.Keeper,\n\tmsg *types.MsgAddPostReaction, ctx sdk.Context, chainID string, privkeys []cryptotypes.PrivKey,\n) error {\n\taddr, _ := sdk.AccAddressFromBech32(msg.User)\n\taccount := ak.GetAccount(ctx, addr)\n\tcoins := bk.SpendableCoins(ctx, account.GetAddress())\n\n\tfees, err := simtypes.RandomFees(r, ctx, coins)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttxGen := simappparams.MakeTestEncodingConfig().TxConfig\n\ttx, err := helpers.GenTx(\n\t\ttxGen,\n\t\t[]sdk.Msg{msg},\n\t\tfees,\n\t\tDefaultGasValue,\n\t\tchainID,\n\t\t[]uint64{account.GetAccountNumber()},\n\t\t[]uint64{account.GetSequence()},\n\t\tprivkeys...,\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, _, err = app.Deliver(txGen.TxEncoder(), tx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (_Dospayment *DospaymentTransactor) ClaimGuardianReward(opts *bind.TransactOpts, guardianAddr common.Address) (*types.Transaction, error) {\n\treturn _Dospayment.contract.Transact(opts, \"claimGuardianReward\", guardianAddr)\n}", "func (s *BasemumpsListener) EnterPostcondition(ctx *PostconditionContext) {}", "func PostConsumptionTimesAdjustment(\n\tnumOfConsumptionOnAuthor int64, paras *param.EvaluateOfContentValueParam) float64 {\n\treturn (1.0/(1.0+math.Exp(\n\t\t(float64(numOfConsumptionOnAuthor)-float64(paras.NumOfConsumptionOnAuthorOffset)))) + 1.0) + 1.0\n}", "func accumulateRewards(config *params.ChainConfig, state *state.DB, header *types.Header) {\n\t// TODO: implement mining rewards\n}", "func (_Token *TokenCaller) BaseReward(opts *bind.CallOpts, index *big.Int) (*big.Int, *big.Int, *big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t\tret1 = new(*big.Int)\n\t\tret2 = new(*big.Int)\n\t)\n\tout := &[]interface{}{\n\t\tret0,\n\t\tret1,\n\t\tret2,\n\t}\n\terr := _Token.contract.Call(opts, out, \"baseReward\", index)\n\treturn *ret0, *ret1, *ret2, err\n}", "func (b *Builder) StartPost(ctx context.Context, rewardAddress types.Address, dataDir string, space uint64) error {\n\tlogger := b.log.WithContext(ctx)\n\tif !atomic.CompareAndSwapInt32(&b.initStatus, InitIdle, InitInProgress) {\n\t\tswitch atomic.LoadInt32(&b.initStatus) {\n\t\tcase InitDone:\n\t\t\treturn fmt.Errorf(\"already initialized\")\n\t\tcase InitInProgress:\n\t\t\treturn fmt.Errorf(\"already started\")\n\t\t}\n\t}\n\n\tif err := b.postProver.SetParams(dataDir, space); err != nil {\n\t\treturn err\n\t}\n\tb.SetCoinbaseAccount(rewardAddress)\n\n\tinitialized, _, err := b.postProver.IsInitialized()\n\tif err != nil {\n\t\tatomic.StoreInt32(&b.initStatus, InitIdle)\n\t\treturn err\n\t}\n\n\tif !initialized {\n\t\tif err := b.postProver.VerifyInitAllowed(); err != nil {\n\t\t\tatomic.StoreInt32(&b.initStatus, InitIdle)\n\t\t\treturn err\n\t\t}\n\t}\n\n\tlogger.With().Info(\"starting post initialization\",\n\t\tlog.String(\"datadir\", dataDir),\n\t\tlog.String(\"space\", fmt.Sprintf(\"%d\", space)),\n\t\tlog.String(\"rewardAddress\", fmt.Sprintf(\"%x\", rewardAddress)),\n\t)\n\n\tgo func() {\n\t\tif initialized {\n\t\t\t// If initialized, run the execution phase with zero-challenge,\n\t\t\t// to create the initial proof (the commitment).\n\t\t\tb.commitment, err = b.postProver.Execute(shared.ZeroChallenge)\n\t\t\tif err != nil {\n\t\t\t\tlogger.With().Error(\"post execution failed\", log.Err(err))\n\t\t\t\tatomic.StoreInt32(&b.initStatus, InitIdle)\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\t// If not initialized, run the initialization phase.\n\t\t\t// This would create the initial proof (the commitment) as well.\n\t\t\tb.commitment, err = b.postProver.Initialize()\n\t\t\tif err != nil {\n\t\t\t\tlogger.With().Error(\"post initialization failed\", log.Err(err))\n\t\t\t\tatomic.StoreInt32(&b.initStatus, InitIdle)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tlogger.With().Info(\"post initialization completed\",\n\t\t\tlog.String(\"datadir\", dataDir),\n\t\t\tlog.String(\"space\", fmt.Sprintf(\"%d\", space)),\n\t\t\tlog.String(\"commitment merkle root\", fmt.Sprintf(\"%x\", b.commitment.MerkleRoot)),\n\t\t)\n\n\t\tatomic.StoreInt32(&b.initStatus, InitDone)\n\t\tclose(b.initDone)\n\t}()\n\n\treturn nil\n}", "func PostHandleMsgValidatorExit(ctx sdk.Context, k keeper.Keeper, msg types.MsgValidatorExit, sideTxResult tmprototypes.SideTxResultType) (*sdk.Result, error) {\n\t// Skip handler if validator exit is not approved\n\tif sideTxResult != tmprototypes.SideTxResultType_YES {\n\t\tk.Logger(ctx).Debug(\"Skipping validator exit since side-tx didn't get yes votes\")\n\t\treturn nil, common.ErrSideTxValidation\n\t}\n\n\t// Check for replay attack\n\tblockNumber := new(big.Int).SetUint64(msg.BlockNumber)\n\tsequence := new(big.Int).Mul(blockNumber, big.NewInt(hmTypes.DefaultLogIndexUnit))\n\tsequence.Add(sequence, new(big.Int).SetUint64(msg.LogIndex))\n\n\t// check if incoming tx is older\n\tif k.HasStakingSequence(ctx, sequence.String()) {\n\t\tk.Logger(ctx).Error(\"Older invalid tx found\")\n\t\treturn nil, hmCommon.ErrOldTx\n\t}\n\n\tk.Logger(ctx).Debug(\"Persisting validator exit\", \"sideTxResult\", sideTxResult)\n\n\tvalidator, ok := k.GetValidatorFromValID(ctx, msg.ID)\n\tif !ok {\n\t\tk.Logger(ctx).Error(\"Fetching of validator from store failed\", \"validatorID\", msg.ID)\n\t\treturn nil, hmCommon.ErrNoValidator\n\t}\n\n\t// set end epoch\n\tvalidator.EndEpoch = msg.DeactivationEpoch\n\n\t// update last updated\n\tvalidator.LastUpdated = sequence.String()\n\n\t// update nonce\n\tvalidator.Nonce = msg.Nonce\n\n\t// Add deactivation time for validator\n\tif err := k.AddValidator(ctx, validator); err != nil {\n\t\tk.Logger(ctx).Error(\"Error while setting deactivation epoch to validator\", \"error\", err, \"validatorID\", validator.ID.String())\n\t\treturn nil, hmCommon.ErrValidatorNotDeactivated\n\t}\n\n\t// save staking sequence\n\tk.SetStakingSequence(ctx, sequence.String())\n\n\t// TX bytes\n\ttxBytes := ctx.TxBytes()\n\thash := tmTypes.Tx(txBytes).Hash()\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeValidatorExit,\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAction, msg.Type()), // action\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), // module name\n\t\t\tsdk.NewAttribute(hmTypes.AttributeKeyTxHash, hmCommonTypes.BytesToHeimdallHash(hash).Hex()), // tx hash\n\t\t\tsdk.NewAttribute(hmTypes.AttributeKeySideTxResult, sideTxResult.String()), // result\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidatorID, validator.ID.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidatorNonce, strconv.FormatUint(msg.Nonce, 10)),\n\t\t),\n\t})\n\n\treturn &sdk.Result{\n\t\tEvents: ctx.EventManager().ABCIEvents(),\n\t}, nil\n}", "func (client CloudEndpointsClient) PostBackupResponder(resp *http.Response) (result PostBackupResponse, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (_Univ2 *Univ2TransactorSession) Permit(owner common.Address, spender common.Address, value *big.Int, deadline *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) {\n\treturn _Univ2.Contract.Permit(&_Univ2.TransactOpts, owner, spender, value, deadline, v, r, s)\n}", "func (_Vault *VaultSession) SubmitBurnProof(inst []byte, heights *big.Int, instPaths [][32]byte, instPathIsLefts []bool, instRoots [32]byte, blkData [32]byte, sigIdxs []*big.Int, sigVs []uint8, sigRs [][32]byte, sigSs [][32]byte) (*types.Transaction, error) {\n\treturn _Vault.Contract.SubmitBurnProof(&_Vault.TransactOpts, inst, heights, instPaths, instPathIsLefts, instRoots, blkData, sigIdxs, sigVs, sigRs, sigSs)\n}", "func (k Keeper) PerformStake(ctx sdk.Context, vendorID uint32, postID curatingtypes.PostID, delAddr sdk.AccAddress,\n\tvalAddr sdk.ValAddress, amount sdk.Int) error {\n\n\tp, found, err := k.curatingKeeper.GetPost(ctx, vendorID, postID)\n\tif !found {\n\t\treturn curatingtypes.ErrPostNotFound\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif ctx.BlockTime().Before(p.CuratingEndTime) {\n\t\treturn types.ErrCurationNotExpired\n\t}\n\n\tstake, found, err := k.GetStake(ctx, vendorID, postID, delAddr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tamt := amount\n\tif found {\n\t\tamt = stake.Amount.Add(amount)\n\t\t// shadow valAddr so we don't mix validators when adding stake\n\t\tvalAddr, err = sdk.ValAddressFromBech32(stake.Validator)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tvalidator, found := k.stakingKeeper.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn stakingtypes.ErrNoValidatorFound\n\t}\n\n\tstake = types.NewStake(vendorID, postID, delAddr, valAddr, amt)\n\tk.SetStake(ctx, delAddr, stake)\n\n\t_, err = k.stakingKeeper.Delegate(ctx, delAddr, amount, stakingtypes.Unbonded, validator, true)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeStake,\n\t\t\tsdk.NewAttribute(types.AttributeKeyVendorID, fmt.Sprintf(\"%d\", vendorID)),\n\t\t\tsdk.NewAttribute(types.AttributeKeyPostID, postID.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyDelegator, delAddr.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, valAddr.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyAmount, amt.String()),\n\t\t),\n\t})\n\n\treturn nil\n}", "func (rig *testRig) ackRedemption_taker(checkSig bool) error {\n\tmatchInfo := rig.matchInfo\n\terr := rig.ackRedemption(matchInfo.taker, matchInfo.takerOID, matchInfo.db.makerRedeem)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif checkSig {\n\t\ttracker := rig.getTracker()\n\t\tif !bytes.Equal(tracker.Sigs.TakerRedeem, matchInfo.taker.sig) {\n\t\t\treturn fmt.Errorf(\"expected taker redemption signature '%x', got '%x'\", matchInfo.taker.sig, tracker.Sigs.TakerRedeem)\n\t\t}\n\t}\n\treturn nil\n}", "func EstimateReward(reward, pr, gamma float64) float64 {\n\tret := reward / (pr + gamma)\n\tlog.Logf(MABLogLevel, \"MAB Estimate Reward: %v / (%v + %v) = %v\\n\",\n\t\treward, pr, gamma, ret)\n\treturn ret\n}", "func (k Querier) Rewards(c context.Context, req *types.QueryRewardsRequest) (*types.QueryRewardsResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"invalid request\")\n\t}\n\n\tif req.StakingCoinDenom != \"\" {\n\t\tif err := sdk.ValidateDenom(req.StakingCoinDenom); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tctx := sdk.UnwrapSDKContext(c)\n\tstore := ctx.KVStore(k.storeKey)\n\tvar rewards []types.Reward\n\tvar pageRes *query.PageResponse\n\tvar err error\n\n\tif req.Farmer != \"\" {\n\t\tvar farmerAcc sdk.AccAddress\n\t\tfarmerAcc, err = sdk.AccAddressFromBech32(req.Farmer)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tstorePrefix := types.GetRewardsByFarmerIndexKey(farmerAcc)\n\t\tindexStore := prefix.NewStore(store, storePrefix)\n\t\tpageRes, err = query.FilteredPaginate(indexStore, req.Pagination, func(key, value []byte, accumulate bool) (bool, error) {\n\t\t\t_, stakingCoinDenom := types.ParseRewardsByFarmerIndexKey(append(storePrefix, key...))\n\t\t\tif req.StakingCoinDenom != \"\" {\n\t\t\t\tif stakingCoinDenom != req.StakingCoinDenom {\n\t\t\t\t\treturn false, nil\n\t\t\t\t}\n\t\t\t}\n\t\t\treward, found := k.GetReward(ctx, stakingCoinDenom, farmerAcc)\n\t\t\tif !found { // TODO: remove this check\n\t\t\t\treturn false, fmt.Errorf(\"reward not found\")\n\t\t\t}\n\t\t\tif accumulate {\n\t\t\t\trewards = append(rewards, reward)\n\t\t\t}\n\t\t\treturn true, nil\n\t\t})\n\t} else {\n\t\tvar storePrefix []byte\n\t\tif req.StakingCoinDenom != \"\" {\n\t\t\tstorePrefix = types.GetRewardsByStakingCoinDenomKey(req.StakingCoinDenom)\n\t\t} else {\n\t\t\tstorePrefix = types.RewardKeyPrefix\n\t\t}\n\t\trewardStore := prefix.NewStore(store, storePrefix)\n\n\t\tpageRes, err = query.Paginate(rewardStore, req.Pagination, func(key, value []byte) error {\n\t\t\tstakingCoinDenom, farmerAcc := types.ParseRewardKey(append(storePrefix, key...))\n\t\t\trewardCoins, err := k.UnmarshalRewardCoins(value)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\trewards = append(rewards, types.Reward{\n\t\t\t\tFarmer: farmerAcc.String(),\n\t\t\t\tStakingCoinDenom: stakingCoinDenom,\n\t\t\t\tRewardCoins: rewardCoins.RewardCoins,\n\t\t\t})\n\t\t\treturn nil\n\t\t})\n\t}\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &types.QueryRewardsResponse{Rewards: rewards, Pagination: pageRes}, nil\n}", "func (_Bindings *BindingsTransactor) Redeem(opts *bind.TransactOpts, redeemTokens *big.Int) (*types.Transaction, error) {\n\treturn _Bindings.contract.Transact(opts, \"redeem\", redeemTokens)\n}", "func computeReward(epoch abi.ChainEpoch, prevTheta, currTheta, simpleTotal, baselineTotal big.Int) abi.TokenAmount {\n\tsimpleReward := big.Mul(simpleTotal, ExpLamSubOne) //Q.0 * Q.128 => Q.128\n\tepochLam := big.Mul(big.NewInt(int64(epoch)), Lambda) // Q.0 * Q.128 => Q.128\n\n\tsimpleReward = big.Mul(simpleReward, big.NewFromGo(math.ExpNeg(epochLam.Int))) // Q.128 * Q.128 => Q.256\n\tsimpleReward = big.Rsh(simpleReward, math.Precision128) // Q.256 >> 128 => Q.128\n\n\tbaselineReward := big.Sub(computeBaselineSupply(currTheta, baselineTotal), computeBaselineSupply(prevTheta, baselineTotal)) // Q.128\n\n\treward := big.Add(simpleReward, baselineReward) // Q.128\n\n\treturn big.Rsh(reward, math.Precision128) // Q.128 => Q.0\n}", "func (g *Group) POST(path string, h Handler, gases ...Gas) {\n\tg.Air.POST(g.Prefix+path, h, append(g.Gases, gases...)...)\n}", "func (transaction *AccountCreateTransaction) GetDeclineStakingReward() bool {\n\treturn transaction.declineReward\n}", "func Submit(\n\tt *testing.T,\n\tb *emulator.Blockchain,\n\ttx *flow.Transaction,\n\tshouldRevert bool,\n) {\n\t// submit the signed transaction\n\terr := b.AddTransaction(*tx)\n\trequire.NoError(t, err)\n\n\tresult, err := b.ExecuteNextTransaction()\n\trequire.NoError(t, err)\n\n\tif shouldRevert {\n\t\tassert.True(t, result.Reverted())\n\t} else {\n\t\tif !assert.True(t, result.Succeeded()) {\n\t\t\tt.Log(result.Error.Error())\n\t\t}\n\t}\n\n\t_, err = b.CommitBlock()\n\tassert.NoError(t, err)\n}", "func Submit(\n\tt *testing.T,\n\tb *emulator.Blockchain,\n\ttx *flow.Transaction,\n\tshouldRevert bool,\n) {\n\t// submit the signed transaction\n\terr := b.AddTransaction(*tx)\n\trequire.NoError(t, err)\n\n\tresult, err := b.ExecuteNextTransaction()\n\trequire.NoError(t, err)\n\n\tif shouldRevert {\n\t\tassert.True(t, result.Reverted())\n\t} else {\n\t\tif !assert.True(t, result.Succeeded()) {\n\t\t\tt.Log(result.Error.Error())\n\t\t}\n\t}\n\n\t_, err = b.CommitBlock()\n\tassert.NoError(t, err)\n}", "func claim(args []string) (string, error) {\n\tamount, err := util.StringToRau(args[0], util.IotxDecimalNum)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tpayload := make([]byte, 0)\n\tif len(args) == 2 {\n\t\tpayload = []byte(args[1])\n\t}\n\tsender, err := alias.Address(signer)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif gasLimit == 0 {\n\t\tgasLimit = action.ClaimFromRewardingFundBaseGas +\n\t\t\taction.ClaimFromRewardingFundGasPerByte*uint64(len(payload))\n\t}\n\tvar gasPriceRau *big.Int\n\tif len(gasPrice) == 0 {\n\t\tgasPriceRau, err = GetGasPrice()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t} else {\n\t\tgasPriceRau, err = util.StringToRau(gasPrice, util.GasPriceDecimalNum)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\tif nonce == 0 {\n\t\taccountMeta, err := account.GetAccountMeta(sender)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tnonce = accountMeta.PendingNonce\n\t}\n\tb := &action.ClaimFromRewardingFundBuilder{}\n\tact := b.SetAmount(amount).SetData(payload).Build()\n\tbd := &action.EnvelopeBuilder{}\n\telp := bd.SetNonce(nonce).\n\t\tSetGasPrice(gasPriceRau).\n\t\tSetGasLimit(gasLimit).\n\t\tSetAction(&act).Build()\n\treturn sendAction(elp)\n}", "func (_Vault *VaultTransactorSession) SubmitBurnProof(inst []byte, heights *big.Int, instPaths [][32]byte, instPathIsLefts []bool, instRoots [32]byte, blkData [32]byte, sigIdxs []*big.Int, sigVs []uint8, sigRs [][32]byte, sigSs [][32]byte) (*types.Transaction, error) {\n\treturn _Vault.Contract.SubmitBurnProof(&_Vault.TransactOpts, inst, heights, instPaths, instPathIsLefts, instRoots, blkData, sigIdxs, sigVs, sigRs, sigSs)\n}", "func (dcr *ExchangeWallet) PreRedeem(req *asset.PreRedeemForm) (*asset.PreRedeem, error) {\n\tfeeRate := req.FeeSuggestion\n\tif feeRate == 0 { // or just document that the caller must set it?\n\t\tfeeRate = dcr.targetFeeRateWithFallback(dcr.redeemConfTarget, req.FeeSuggestion)\n\t}\n\t// Best is one transaction with req.Lots inputs and 1 output.\n\tvar best uint64 = dexdcr.MsgTxOverhead\n\t// Worst is req.Lots transactions, each with one input and one output.\n\tvar worst uint64 = dexdcr.MsgTxOverhead * req.Lots\n\tvar inputSize uint64 = dexdcr.TxInOverhead + dexdcr.RedeemSwapSigScriptSize\n\tvar outputSize uint64 = dexdcr.P2PKHOutputSize\n\tbest += inputSize*req.Lots + outputSize\n\tworst += (inputSize + outputSize) * req.Lots\n\n\t// Read the order options.\n\tcustomCfg := new(redeemOptions)\n\terr := config.Unmapify(req.SelectedOptions, customCfg)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing selected options: %w\", err)\n\t}\n\n\t// Parse the configured fee bump.\n\tvar currentBump float64 = 1.0\n\tif customCfg.FeeBump != nil {\n\t\tbump := *customCfg.FeeBump\n\t\tif bump < 1.0 || bump > 2.0 {\n\t\t\treturn nil, fmt.Errorf(\"invalid fee bump: %f\", bump)\n\t\t}\n\t\tcurrentBump = bump\n\t}\n\n\topts := []*asset.OrderOption{{\n\t\tConfigOption: asset.ConfigOption{\n\t\t\tKey: redeemFeeBumpFee,\n\t\t\tDisplayName: \"Faster Redemption\",\n\t\t\tDescription: \"Bump the redemption transaction fees up to 2x for faster confirmations on your redemption transaction.\",\n\t\t\tDefaultValue: 1.0,\n\t\t},\n\t\tXYRange: &asset.XYRange{\n\t\t\tStart: asset.XYRangePoint{\n\t\t\t\tLabel: \"1X\",\n\t\t\t\tX: 1.0,\n\t\t\t\tY: float64(feeRate),\n\t\t\t},\n\t\t\tEnd: asset.XYRangePoint{\n\t\t\t\tLabel: \"2X\",\n\t\t\t\tX: 2.0,\n\t\t\t\tY: float64(feeRate * 2),\n\t\t\t},\n\t\t\tYUnit: \"atoms/B\",\n\t\t\tXUnit: \"X\",\n\t\t},\n\t}}\n\n\treturn &asset.PreRedeem{\n\t\tEstimate: &asset.RedeemEstimate{\n\t\t\tRealisticWorstCase: uint64(math.Round(float64(worst*feeRate) * currentBump)),\n\t\t\tRealisticBestCase: uint64(math.Round(float64(best*feeRate) * currentBump)),\n\t\t},\n\t\tOptions: opts,\n\t}, nil\n}", "func (bc *blockchain) TransferBurst(senderPublicKey []byte, receiverId uint64, amount, fee int64) error {\n\ttotalAmount := amount + fee\n\treturn bc.db.Update(func(txn *badger.Txn) error {\n\t\t// senderPublicKey nil -> block forge\n\t\tif senderPublicKey != nil {\n\t\t\tsender, err := bc.getAccountByPublicKey(txn, senderPublicKey)\n\t\t\tswitch err {\n\t\t\tcase nil:\n\t\t\tcase badger.ErrKeyNotFound:\n\t\t\t\t// an account only gets a public key on its first outgoing transaction\n\t\t\t\t// so we need to check if we can find it by numeric id\n\t\t\t\t_, id := crypto.BytesToHashAndID(senderPublicKey)\n\t\t\t\tswitch sender, err = bc.getAccountById(txn, id); err {\n\t\t\t\tcase nil:\n\t\t\t\t\t// we found the account by numeric id, but not by public key\n\t\t\t\t\t// this is the account's first outgoing transaction\n\t\t\t\t\t// we can no activate it by setting its public key\n\t\t\t\t\tsender.PublicKey = senderPublicKey\n\n\t\t\t\t\t// to be retrievable by public key we need to add it to\n\t\t\t\t\t// the account index\n\t\t\t\t\tif err := bc.indexAccountsPublicKey(txn, sender); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\tcase badger.ErrKeyNotFound:\n\t\t\t\t\treturn ErrUnknownAccount\n\t\t\t\tdefault:\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn err\n\n\t\t\t}\n\n\t\t\tif sender.Balance < totalAmount {\n\t\t\t\treturn ErrBalanceTooLow\n\t\t\t}\n\t\t\tsender.Balance -= totalAmount\n\t\t\tif err := bc.updateAccount(txn, sender); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\treceiver, err := bc.getAccountById(txn, receiverId)\n\t\tswitch err {\n\t\tcase nil:\n\t\t\t// if this is a block forge transfer -> reward recipient handling\n\t\t\tif senderPublicKey == nil && receiver.RewardRecipient != receiver.Id {\n\t\t\t\treceiver, err = bc.getAccountById(txn, receiverId)\n\t\t\t\tswitch err {\n\t\t\t\tcase nil:\n\t\t\t\tcase badger.ErrKeyNotFound:\n\t\t\t\t\treceiver = account.NewAccount(receiverId)\n\t\t\t\tdefault:\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\tcase badger.ErrKeyNotFound:\n\t\t\t// receiver did not exist yet, so its a new account that still\n\t\t\t// needs to get activated with an outgoing transaction\n\t\t\treceiver = account.NewAccount(receiverId)\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t\treceiver.Balance += amount\n\n\t\treturn bc.updateAccount(txn, receiver)\n\t})\n}", "func ApprovePost(id string) error {\n\t_, err := db.Query(\"UPDATE furmpost SET adApproval=? WHERE entryID=?\", 1, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func PostHandleMsgSignerUpdate(ctx sdk.Context, k keeper.Keeper, msg types.MsgSignerUpdate, sideTxResult tmprototypes.SideTxResultType) (*sdk.Result, error) {\n\t// Skip handler if signer update is not approved\n\tif sideTxResult != tmprototypes.SideTxResultType_YES {\n\t\tk.Logger(ctx).Debug(\"Skipping signer update since side-tx didn't get yes votes\")\n\t\treturn nil, hmCommon.ErrSideTxValidation\n\t}\n\n\t// Check for replay attack\n\tblockNumber := new(big.Int).SetUint64(msg.BlockNumber)\n\tsequence := new(big.Int).Mul(blockNumber, big.NewInt(hmTypes.DefaultLogIndexUnit))\n\tsequence.Add(sequence, new(big.Int).SetUint64(msg.LogIndex))\n\t// check if incoming tx is older\n\tif k.HasStakingSequence(ctx, sequence.String()) {\n\t\tk.Logger(ctx).Error(\"Older invalid tx found\")\n\t\treturn nil, hmCommon.ErrOldTx\n\t}\n\n\tk.Logger(ctx).Debug(\"Persisting signer update\", \"sideTxResult\", sideTxResult)\n\n\t// new pubkey and signer\n\tnewPubKey := msg.GetNewSignerPubKey()\n\tnewSigner := newPubKey.Address()\n\n\t// pull validator from store\n\tvalidator, ok := k.GetValidatorFromValID(ctx, msg.ID)\n\tif !ok {\n\t\tk.Logger(ctx).Error(\"Fetching of validator from store failed\", \"validatorId\", msg.ID)\n\t\treturn nil, hmCommon.ErrNoValidator\n\t}\n\toldValidator := validator.Copy()\n\n\t// update last updated\n\tvalidator.LastUpdated = sequence.String()\n\n\t// update nonce\n\tvalidator.Nonce = msg.Nonce\n\n\t// check if we are actually updating signer\n\tif !bytes.Equal(newSigner.Bytes(), []byte(validator.Signer)) {\n\t\t// Update signer in prev Validator\n\t\tvalidator.Signer = newSigner.String()\n\t\tvalidator.PubKey = newPubKey.String()\n\t\tk.Logger(ctx).Debug(\"Updating new signer\", \"newSigner\", newSigner, \"oldSigner\", oldValidator.Signer, \"validatorID\", msg.ID)\n\t} else {\n\t\tk.Logger(ctx).Error(\"No signer change\", \"newSigner\", newSigner, \"oldSigner\", oldValidator.Signer, \"validatorID\", msg.ID)\n\t\treturn nil, hmCommon.ErrSignerUpdateError\n\t}\n\n\tk.Logger(ctx).Debug(\"Removing old validator\", \"validator\", oldValidator.String())\n\n\t// remove old validator from HM\n\toldValidator.EndEpoch = k.ModuleCommunicator.GetACKCount(ctx)\n\n\t// remove old validator from TM\n\toldValidator.VotingPower = 0\n\t// updated last\n\toldValidator.LastUpdated = sequence.String()\n\n\t// updated nonce\n\toldValidator.Nonce = msg.Nonce\n\n\t// save old validator\n\tif err := k.AddValidator(ctx, *oldValidator); err != nil {\n\t\tk.Logger(ctx).Error(\"Unable to update signer\", \"error\", err, \"validatorId\", validator.ID)\n\t\treturn nil, hmCommon.ErrSignerUpdateError\n\t}\n\n\t// adding new validator\n\tk.Logger(ctx).Debug(\"Adding new validator\", \"validator\", validator.String())\n\n\t// save validator\n\terr := k.AddValidator(ctx, validator)\n\tif err != nil {\n\t\tk.Logger(ctx).Error(\"Unable to update signer\", \"error\", err, \"ValidatorID\", validator.ID)\n\t\treturn nil, hmCommon.ErrSignerUpdateError\n\t}\n\n\t// save staking sequence\n\tk.SetStakingSequence(ctx, sequence.String())\n\n\t// TX bytes\n\ttxBytes := ctx.TxBytes()\n\thash := tmTypes.Tx(txBytes).Hash()\n\n\t//\n\t// Move heimdall fee to new signer\n\t//\n\n\t// check if fee is already withdrawn\n\tmaticBalance := k.BankKeeper.GetBalance(ctx, sdk.AccAddress([]byte(oldValidator.Signer)), types.FeeToken)\n\tif !maticBalance.IsZero() {\n\t\tk.Logger(ctx).Info(\"Transferring fee\", \"from\", oldValidator.Signer, \"to\", validator.Signer, \"balance\", maticBalance.String())\n\t\tmaticCoins := sdk.Coins{maticBalance}\n\t\tif err := k.BankKeeper.SendCoins(ctx, sdk.AccAddress([]byte(oldValidator.Signer)), sdk.AccAddress([]byte(validator.Signer)), maticCoins); err != nil {\n\t\t\tk.Logger(ctx).Info(\"Error while transferring fee\", \"from\", oldValidator.Signer, \"to\", validator.Signer, \"balance\", maticBalance.String())\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeSignerUpdate,\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAction, msg.Type()), // action\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), // module name\n\t\t\tsdk.NewAttribute(hmTypes.AttributeKeyTxHash, hmCommonTypes.BytesToHeimdallHash(hash).Hex()), // tx hash\n\t\t\tsdk.NewAttribute(hmTypes.AttributeKeySideTxResult, sideTxResult.String()), // result\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidatorID, validator.ID.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidatorNonce, strconv.FormatUint(msg.Nonce, 10)),\n\t\t),\n\t})\n\n\treturn &sdk.Result{\n\t\tEvents: ctx.EventManager().ABCIEvents(),\n\t}, nil\n}", "func (_Contract *ContractCaller) TaskHandlingReward(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Contract.contract.Call(opts, &out, \"taskHandlingReward\")\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 PostSlotTransition(ctx context.Context, spec *Spec, epc *EpochsContext, state BeaconState, benv *BeaconBlockEnvelope, validateResult bool) error {\n\tslot, err := state.Slot()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif slot != benv.Slot {\n\t\treturn fmt.Errorf(\"transition of block, post-slot-processing, must run on state with same slot\")\n\t}\n\tif validateResult {\n\t\t// TODO: tests have invalid fork version in state\n\t\tfork, err := state.Fork()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t//version := spec.ForkVersion(benv.Slot)\n\t\t//if fork.CurrentVersion != version {\n\t\t//\treturn fmt.Errorf(\"state does not have expected fork version of block slot: %s <> %s (slot %d)\",\n\t\t//\t\tfork.CurrentVersion, version, benv.Slot)\n\t\t//}\n\t\tproposer, err := epc.GetBeaconProposer(benv.Slot)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tgenValRoot, err := state.GenesisValidatorsRoot()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpub, ok := epc.ValidatorPubkeyCache.Pubkey(proposer)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unknown pubkey for proposer %d\", proposer)\n\t\t}\n\t\tif !benv.VerifySignatureVersioned(spec, fork.CurrentVersion, genValRoot, proposer, pub) {\n\t\t\treturn errors.New(\"block has invalid signature\")\n\t\t}\n\t}\n\tif err := state.ProcessBlock(ctx, spec, epc, benv); err != nil {\n\t\treturn err\n\t}\n\n\t// State root verification\n\tif validateResult && benv.StateRoot != state.HashTreeRoot(tree.GetHashFn()) {\n\t\treturn errors.New(\"block has invalid state root\")\n\t}\n\treturn nil\n}", "func (a *StoragePowerActorCode_I) AddBalance(rt Runtime, minerAddr addr.Address) {\n\tRT_MinerEntry_ValidateCaller_DetermineFundsLocation(rt, minerAddr, vmr.MinerEntrySpec_MinerOnly)\n\n\tmsgValue := rt.ValueReceived()\n\n\th, st := a.State(rt)\n\tnewTable, ok := autil.BalanceTable_WithAdd(st.EscrowTable(), minerAddr, msgValue)\n\tif !ok {\n\t\trt.AbortStateMsg(\"Escrow operation failed\")\n\t}\n\tst.Impl().EscrowTable_ = newTable\n\tUpdateRelease(rt, h, st)\n}", "func SenderHtlcSpendRedeem(signer Signer, signDesc *SignDescriptor,\n\tsweepTx *wire.MsgTx, paymentPreimage []byte) (wire.TxWitness, error) {\n\n\tsweepSig, err := signer.SignOutputRaw(sweepTx, signDesc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// The stack required to spend this output is simply the signature\n\t// generated above under the receiver's public key, and the payment\n\t// pre-image.\n\twitnessStack := wire.TxWitness(make([][]byte, 3))\n\twitnessStack[0] = append(sweepSig.Serialize(), byte(signDesc.HashType))\n\twitnessStack[1] = paymentPreimage\n\twitnessStack[2] = signDesc.WitnessScript\n\n\treturn witnessStack, nil\n}", "func (client CloudEndpointsClient) PostRestoreResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (sp *SimulatedPlayer) Redeem(cs *markets.ContractSet, m *markets.Market, v bool) {\n\tsp.mp.Redeem(cs, m, v)\n}", "func (b *Builder) Post(addr value.Pointer, size uint64, p Postback) {\n\tif !addr.IsValid() {\n\t\tpanic(fmt.Errorf(\"Pointer address %v is not valid\", addr))\n\t}\n\tb.instructions = append(b.instructions, asm.Post{\n\t\tSource: b.remap(addr),\n\t\tSize: size,\n\t})\n\tb.decoders = append(b.decoders, postBackDecoder{\n\t\texpectedSize: int(size),\n\t\tdecode: p,\n\t})\n}", "func (s *State) returnDeposit(tx *types.Transaction, height uint32) {\n\tvar inputValue common.Fixed64\n\tfor _, input := range tx.Inputs {\n\t\tinputValue += s.DepositOutputs[input.ReferKey()]\n\t}\n\n\treturnAction := func(producer *Producer) {\n\t\ts.history.Append(height, func() {\n\t\t\tif height >= s.chainParams.CRVotingStartHeight {\n\t\t\t\tproducer.depositAmount -= inputValue\n\t\t\t}\n\t\t\tproducer.state = Returned\n\t\t}, func() {\n\t\t\tif height >= s.chainParams.CRVotingStartHeight {\n\t\t\t\tproducer.depositAmount += inputValue\n\t\t\t}\n\t\t\tproducer.state = Canceled\n\t\t})\n\t}\n\n\tfor _, program := range tx.Programs {\n\t\tpk := program.Code[1 : len(program.Code)-1]\n\t\tif producer := s.getProducer(pk); producer != nil && producer.state == Canceled {\n\t\t\treturnAction(producer)\n\t\t}\n\t}\n}", "func (_RandomBeacon *RandomBeaconTransactor) WithdrawRewards(opts *bind.TransactOpts, stakingProvider common.Address) (*types.Transaction, error) {\n\treturn _RandomBeacon.contract.Transact(opts, \"withdrawRewards\", stakingProvider)\n}", "func (_Smartchef *SmartchefTransactor) EmergencyRewardWithdraw(opts *bind.TransactOpts, _amount *big.Int) (*types.Transaction, error) {\n\treturn _Smartchef.contract.Transact(opts, \"emergencyRewardWithdraw\", _amount)\n}", "func (testSuite *MainTestSuite) flipStockPost(gameStateID uuid.UUID) {\n\tresp, err := testSuite.client.Post(\n\t\taddGameStateIdToURL(testSuite.server.URL+\"/flipstock\", gameStateID),\n\t\t\"text/json\", nil)\n\t_ = err // silence warning about using defer before checking err\n\tdefer resp.Body.Close()\n\tcheckResponse(testSuite.T(), resp, err)\n}" ]
[ "0.7543883", "0.6046861", "0.59213", "0.5888484", "0.569692", "0.5377273", "0.53159016", "0.51158017", "0.5068981", "0.49706677", "0.49703842", "0.49670628", "0.49598822", "0.49169713", "0.49141806", "0.49058503", "0.49056473", "0.48940882", "0.48806125", "0.4861055", "0.48592457", "0.48581138", "0.4853659", "0.4821137", "0.4811574", "0.4793853", "0.478681", "0.47858256", "0.47816804", "0.47714853", "0.4768141", "0.47667566", "0.47511724", "0.4748677", "0.47452414", "0.4744874", "0.47343495", "0.47282892", "0.47150448", "0.47117317", "0.47064444", "0.46983626", "0.46933407", "0.46906152", "0.46857974", "0.4685569", "0.46759397", "0.46676412", "0.46427146", "0.4630347", "0.46227887", "0.46189213", "0.46159413", "0.46077064", "0.4600528", "0.45919168", "0.45901904", "0.45850074", "0.458095", "0.4578385", "0.45707613", "0.4567512", "0.45659444", "0.4543624", "0.4539644", "0.4531277", "0.45096242", "0.45085186", "0.45051596", "0.449541", "0.44850242", "0.44830614", "0.4480382", "0.44769728", "0.44707495", "0.44684407", "0.44483754", "0.4441326", "0.44314894", "0.4431174", "0.4428727", "0.4423487", "0.4423487", "0.44230554", "0.44195634", "0.44194564", "0.44081748", "0.4402279", "0.43986595", "0.43875456", "0.43864027", "0.4386081", "0.43761623", "0.43570605", "0.43476427", "0.43471706", "0.4342304", "0.43381238", "0.43370718", "0.43354195" ]
0.7991568
0
NewDiamond builds a new diamond instance. The default diamond gets populated with a random KSUID as diamondID. Default diamond has cnflicts handling enabled.
NewDiamond создает новый экземпляр даймонда. Стандартный даймонд заполняется случайным KSUID в качестве diamondID. Стандартный даймонд имеет включенной обработку конфликтов.
func NewDiamond(repo string, stores context2.Stores, opts ...DiamondOption) *Diamond { diamond := defaultDiamond(repo, stores) for _, apply := range opts { apply(diamond) } if diamond.deconflicter == nil { // points to the appropriate metadata path rendering function from model, // depending on the conflicts handling mode selected. switch diamond.DiamondDescriptor.Mode { case model.EnableCheckpoints: diamond.deconflicter = model.GenerateCheckpointPath case model.ForbidConflicts: diamond.deconflicter = func(a, b string) string { diamond.l.Error("dev error: deconflicter called in inadequate context", zap.String("arg", a), zap.String("arg", b)) panic("dev error: must not call deconflicter") } case model.EnableConflicts: fallthrough default: diamond.deconflicter = model.GenerateConflictPath } } if diamond.DiamondDescriptor.Tag != "" { diamond.l = diamond.l.With(zap.String("tag", diamond.DiamondDescriptor.Tag)) diamond.Bundle.l = diamond.l } if diamond.MetricsEnabled() { diamond.m = diamond.EnsureMetrics("core", &M{}).(*M) } return diamond }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CreateDiamond(repo string, stores context2.Stores, opts ...DiamondOption) (model.DiamondDescriptor, error) {\n\tvar err error\n\td := NewDiamond(repo, stores, opts...)\n\n\tdefer func(t0 time.Time) {\n\t\tif d.MetricsEnabled() {\n\t\t\td.m.Usage.UsedAll(t0, \"CreateDiamond\")(err)\n\t\t}\n\t}(time.Now())\n\n\tif d.DiamondDescriptor.DiamondID == \"\" {\n\t\treturn model.DiamondDescriptor{}, errors.New(\"a diamond must have a diamondID\")\n\t}\n\n\tif err = RepoExists(repo, stores); err != nil {\n\t\treturn model.DiamondDescriptor{}, err\n\t}\n\n\terr = d.uploadDescriptor()\n\tif err != nil {\n\t\treturn model.DiamondDescriptor{},\n\t\t\terrors.New(\"cannot update diamond descriptor\").Wrap(err)\n\t}\n\treturn d.DiamondDescriptor, nil\n}", "func buildDiamond(cfgraph *CFG, start int) int {\n\tbb0 := start\n\tNewBasicBlockEdge(cfgraph, bb0, bb0+1)\n\tNewBasicBlockEdge(cfgraph, bb0, bb0+2)\n\tNewBasicBlockEdge(cfgraph, bb0+1, bb0+3)\n\tNewBasicBlockEdge(cfgraph, bb0+2, bb0+3)\n\n\treturn bb0 + 3\n}", "func (in *Diamond) DeepCopy() *Diamond {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Diamond)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func DiamondID(id string) DiamondDescriptorOption {\n\treturn func(d *DiamondDescriptor) {\n\t\tif id != \"\" {\n\t\t\td.DiamondID = id\n\t\t}\n\t}\n}", "func GetDiamond(repo, diamondID string, stores context2.Stores, opts ...DiamondOption) (model.DiamondDescriptor, error) {\n\tvar err error\n\n\tgetOpts := []DiamondOption{\n\t\tDiamondDescriptor(\n\t\t\tmodel.NewDiamondDescriptor(model.DiamondID(diamondID)),\n\t\t),\n\t}\n\tgetOpts = append(getOpts, opts...)\n\n\td := NewDiamond(repo, stores, getOpts...)\n\n\tdefer func(t0 time.Time) {\n\t\tif d.MetricsEnabled() {\n\t\t\td.m.Usage.UsedAll(t0, \"GetDiamond\")(err)\n\t\t}\n\t}(time.Now())\n\n\tif err = RepoExists(repo, stores); err != nil {\n\t\treturn model.DiamondDescriptor{}, err\n\t}\n\n\tif err = d.downloadDescriptor(); err != nil {\n\t\treturn model.DiamondDescriptor{}, err\n\t}\n\treturn d.DiamondDescriptor, nil\n}", "func NewGarden(diagram string, children []string) (*Garden, error) {\n\t// Normalize the diagram.\n\tdiagramTrimmed := strings.Trim(diagram, \"\\n\")\n\tif diagramTrimmed == diagram {\n\t\treturn nil, errors.New(\"diagram didn't start with a newline\")\n\t}\n\trows := strings.Split(diagramTrimmed, \"\\n\")\n\tif len(rows) != 2 {\n\t\treturn nil, errors.New(\"invalid number of rows in diagram\")\n\t}\n\tif len(rows[0]) != len(rows[1]) {\n\t\treturn nil, errors.New(\"diagram row lengths do not match\")\n\t}\n\tif len(rows[0]) != 2*len(children) {\n\t\treturn nil, errors.New(\"diagram rows are not the correct length\")\n\t}\n\tfor i := 0; i < len(rows[0]); i++ {\n\t\tc1 := rows[0][i]\n\t\tc2 := rows[1][i]\n\t\tif c1 != 'G' && c1 != 'C' && c1 != 'R' && c1 != 'V' {\n\t\t\treturn nil, errors.New(\"invalid symbol in diagram\")\n\t\t}\n\t\tif c2 != 'G' && c2 != 'C' && c2 != 'R' && c2 != 'V' {\n\t\t\treturn nil, errors.New(\"invalid symbol in diagram\")\n\t\t}\n\t}\n\t// Make a copy of the input array and sort it.\n\tchildrenCopy := make([]string, len(children))\n\tcopy(childrenCopy, children)\n\tsort.Strings(childrenCopy)\n\t// Make sure all children are unique.\n\tfor i := 1; i < len(childrenCopy); i++ {\n\t\tif childrenCopy[i-1] == childrenCopy[i] {\n\t\t\treturn nil, errors.New(\"same child name seen more than once\")\n\t\t}\n\t}\n\t// Add each child to the Garden, and their plants.\n\tg := make(Garden)\n\tfor i, r := range rows[0] {\n\t\tchildName := childrenCopy[i/2]\n\t\tg[childName] = append(g[childName], lookupPlant(r))\n\t}\n\tfor i, r := range rows[1] {\n\t\tchildName := childrenCopy[i/2]\n\t\tg[childName] = append(g[childName], lookupPlant(r))\n\t}\n\treturn &g, nil\n}", "func NewGarden(diagram string, children []string) (*Garden, error) {\n\tg := &Garden{}\n\n\tg.children = make([]string, len(children))\n\tcopy(g.children, children)\n\tsort.Strings(g.children)\n\n\tg.diagram = strings.Split(diagram, \"\\n\")\n\tif len(g.diagram) != 3 {\n\t\treturn nil, errors.New(\"bad diagram\")\n\t}\n\n\tif len(g.diagram[1])%2 != 0 || len(g.diagram[2])%2 != 0 {\n\t\treturn nil, errors.New(\"bad len diagram\")\n\t}\n\n\tif strings.ToLower(g.diagram[1]) == g.diagram[1] || strings.ToLower(g.diagram[2]) == g.diagram[2] {\n\t\treturn nil, errors.New(\"bad caps diagram\")\n\t}\n\n\tg.indexes = make(map[string]int, len(g.children))\n\tfor i, c := range g.children {\n\t\tif c == \"\" {\n\t\t\treturn nil, errors.New(\"no children\")\n\t\t}\n\t\tif _, ok := g.indexes[c]; ok {\n\t\t\treturn nil, errors.New(\"children exists\")\n\t\t}\n\t\tg.indexes[c] = i + 1\n\t}\n\n\treturn g, nil\n}", "func NewDrand(s key.Store, g *key.Group, c *Config) (*Drand, error) {\n\td, err := initDrand(s, c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdkgConf := &dkg.Config{\n\t\tSuite: key.G2.(dkg.Suite),\n\t\tGroup: g,\n\t\tTimeout: d.opts.dkgTimeout,\n\t}\n\td.dkg, err = dkg.NewHandler(d.priv, dkgConf, d.dkgNetwork())\n\td.group = g\n\treturn d, err\n}", "func New(id string) (*D, error) {\n\tc := &mdcD.D{}\n\tif id == \"\" {\n\t\tid = DefaultID\n\t}\n\treturn &D{\n\t\tD: c,\n\t\tIdentity: id,\n\t\tRole: \"dialog\",\n\t\tAcceptBtn: \"Accept\",\n\t\tCancelBtn: \"Deny\",\n\t}, nil\n}", "func newDam() *dam {\n\treturn &dam{\n\t\tlock: sync.RWMutex{},\n\t\tbarrier: make(chan error),\n\t}\n}", "func NewDiamClient(opt *DiamOpt) *DiamClient {\n\tcfg := &sm.Settings{\n\t\tOriginHost: datatype.DiameterIdentity(opt.originHost),\n\t\tOriginRealm: datatype.DiameterIdentity(opt.originRealm),\n\t\tVendorID: datatype.Unsigned32(opt.vendorID),\n\t\tProductName: datatype.UTF8String(opt.productName),\n\t\tOriginStateID: datatype.Unsigned32(time.Now().Unix()),\n\t\tFirmwareRevision: datatype.Unsigned32(opt.firmwareRevision),\n\t\tHostIPAddresses: []datatype.Address{\n\t\t\tdatatype.Address(net.ParseIP(opt.hostAddress)),\n\t\t},\n\t}\n\n\tmux := sm.New(cfg)\n\n\tcli := &sm.Client{\n\t\tDict: dict.Default,\n\t\tHandler: mux,\n\t\tMaxRetransmits: 0,\n\t\tRetransmitInterval: time.Second,\n\t\tEnableWatchdog: true,\n\t\tWatchdogInterval: time.Duration(opt.watchdogInterval) * time.Second,\n\t\tSupportedVendorID: []*diam.AVP{\n\t\t\tdiam.NewAVP(avp.SupportedVendorID, avp.Mbit, 0, datatype.Unsigned32(opt.vendorID)),\n\t\t},\n\t\tVendorSpecificApplicationID: []*diam.AVP{\n\t\t\tdiam.NewAVP(avp.VendorSpecificApplicationID, avp.Mbit, 0, &diam.GroupedAVP{\n\t\t\t\tAVP: []*diam.AVP{\n\t\t\t\t\tdiam.NewAVP(avp.AuthApplicationID, avp.Mbit, 0, datatype.Unsigned32(opt.AppID())),\n\t\t\t\t\tdiam.NewAVP(avp.VendorID, avp.Mbit, 0, datatype.Unsigned32(opt.vendorID)),\n\t\t\t\t},\n\t\t\t}),\n\t\t},\n\t}\n\n\tdone := make(chan struct{}, 1000)\n\tmux.HandleIdx(\n\t\tdiam.CommandIndex{AppID: diam.TGPP_S6A_APP_ID, Code: diam.AuthenticationInformation, Request: false},\n\t\thandleAuthenticationInformationAnswer(done))\n\tmux.HandleIdx(\n\t\tdiam.CommandIndex{AppID: diam.TGPP_S6A_APP_ID, Code: diam.UpdateLocation, Request: false},\n\t\thandleUpdateLocationAnswer(done))\n\tmux.HandleIdx(diam.ALL_CMD_INDEX, handleAll())\n\n\treturn &DiamClient{\n\t\tcli: cli,\n\t\topt: opt,\n\t\tcfg: cfg,\n\t\tdone: done,\n\t}\n}", "func (d *DiamondMiner) doAutoBidForMyDiamond() {\n\t//fmt.Println(\"- doAutoBidForMyDiamond\")\n\n\tfirstFeeTxs := d.txpool.GetDiamondCreateTxs(1) // 取出第一枚钻石挖掘交易\n\tif firstFeeTxs == nil || len(firstFeeTxs) == 0 {\n\t\treturn // No diamonds\n\t}\n\tfirstFeeTx := firstFeeTxs[0]\n\t// Address to give up competition\n\tfor _, iaddr := range d.Config.AutoBidIgnoreAddresses {\n\t\tif bytes.Compare(firstFeeTx.GetAddress(), *iaddr) == 0 {\n\t\t\tif !d.Config.Continued {\n\t\t\t\t// In case of discontinuous mining, stop the mining of this machine\n\t\t\t\t//fmt.Println(\"diamond miner stop all, because fee addr:\", iaddr.ToReadable())\n\t\t\t\td.StopAll()\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n\t// I came first\n\tif bytes.Compare(firstFeeTx.GetAddress(), d.Config.FeeAccount.Address) == 0 {\n\t\tif !d.Config.Continued {\n\t\t\t// In case of discontinuous mining, stop the mining of this machine\n\t\t\t//fmt.Println(\"diamond miner stop all, because fee addr:\", firstFeeTx.GetAddress().ToReadable())\n\t\t\td.StopAll()\n\t\t}\n\t\treturn\n\t}\n\tif d.currentSuccessMiningDiamondTx == nil {\n\t\treturn\n\t}\n\t// Compare diamond serial numbers\n\tcuract := transactions.CheckoutAction_4_DiamondCreateFromTx(d.currentSuccessMiningDiamondTx)\n\tfirstact := transactions.CheckoutAction_4_DiamondCreateFromTx(firstFeeTx.(interfacev2.Transaction))\n\tif curact == nil || firstact == nil {\n\t\treturn\n\t}\n\tif curact.Number != firstact.Number {\n\t\td.currentSuccessMiningDiamondTx = nil // Invalid mining\n\t\treturn\n\t}\n\n\t// Start bidding\n\ttopfee := firstFeeTx.GetFee()\n\tmyfee, e1 := topfee.Add(d.Config.AutoBidMarginFee)\n\tif e1 != nil {\n\t\tfmt.Println(\"doAutoBidForMyDiamond Error:\", e1)\n\t\treturn\n\t}\n\tif newmyfee, _, e2 := myfee.CompressForMainNumLen(4, true); e2 == nil && newmyfee != nil {\n\t\tmyfee = newmyfee // Up compression length\n\t}\n\t// Is it higher than the maximum price I set\n\tif d.Config.AutoBidMaxFee.LessThan(topfee) {\n\t\treturn\n\t}\n\tif d.Config.AutoBidMaxFee.LessThan(myfee) {\n\t\tmyfee = d.Config.AutoBidMaxFee // The highest price has been reached\n\t}\n\n\t// Update transaction fee\n\tnewtx := d.currentSuccessMiningDiamondTx\n\tnewtx.SetFee(myfee)\n\tnewtx.ClearHash() // Reset hash cache\n\t// Private key\n\tallPrivateKeyBytes := make(map[string][]byte, 1)\n\tallPrivateKeyBytes[string(d.Config.FeeAccount.Address)] = d.Config.FeeAccount.PrivateKey\n\t// do sign\n\tnewtx.FillNeedSigns(allPrivateKeyBytes, nil)\n\t// add to pool\n\terr4 := d.txpool.AddTx(newtx.(interfaces.Transaction))\n\tif err4 != nil {\n\t\tfmt.Println(\"doAutoBidForMyDiamond Add to Tx Pool, Error: \", err4.Error())\n\t\treturn\n\t}\n\n\t// success\n\tfmt.Printf(\"diamond auto bid name: <%s>, tx: <%s>, fee: %s => %s \\n\",\n\t\tstring(curact.Diamond), newtx.Hash().ToHex(),\n\t\ttopfee.ToFinString(), myfee.ToFinString(),\n\t)\n}", "func DiamondClone(m DiamondDescriptor) DiamondDescriptorOption {\n\treturn func(d *DiamondDescriptor) {\n\t\t*d = m\n\t}\n}", "func NewDiscriminator(disc *low.Discriminator) *Discriminator {\n\td := new(Discriminator)\n\td.low = disc\n\td.PropertyName = disc.PropertyName.Value\n\tmapping := make(map[string]string)\n\tfor k, v := range disc.Mapping.Value {\n\t\tmapping[k.Value] = v.Value\n\t}\n\td.Mapping = mapping\n\treturn d\n}", "func NewDI() DIer {\n\td := new(DI)\n\td.store = make(map[string]interface{})\n\treturn d\n}", "func NewD(opts ...Option) *D {\n\td := &D{\n\t\tconfig: DefaultConfig(),\n\t\tdata: newData(),\n\t\tstopCh: make(chan struct{}),\n\t}\n\tfor _, opt := range opts {\n\t\topt(d)\n\t}\n\n\treturn d\n}", "func newDiseaseMutation(c config, op Op, opts ...diseaseOption) *DiseaseMutation {\n\tm := &DiseaseMutation{\n\t\tconfig: c,\n\t\top: op,\n\t\ttyp: TypeDisease,\n\t\tclearedFields: make(map[string]struct{}),\n\t}\n\tfor _, opt := range opts {\n\t\topt(m)\n\t}\n\treturn m\n}", "func newDiseaseMutation(c config, op Op, opts ...diseaseOption) *DiseaseMutation {\n\tm := &DiseaseMutation{\n\t\tconfig: c,\n\t\top: op,\n\t\ttyp: TypeDisease,\n\t\tclearedFields: make(map[string]struct{}),\n\t}\n\tfor _, opt := range opts {\n\t\topt(m)\n\t}\n\treturn m\n}", "func NewDog(color string, height int, name string) Dog {\n\treturn Dog{color: color, height: height, name: name}\n}", "func NewDex(creator Name, staking Coins, description string) *Dex {\n\treturn &Dex{\n\t\tCreator: creator,\n\t\tStaking: staking,\n\t\tDescription: description,\n\t}\n}", "func (in *DiamondSpec) DeepCopy() *DiamondSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DiamondSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *DiamondConfig) DeepCopy() *DiamondConfig {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DiamondConfig)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func DiamondTag(tag string) DiamondDescriptorOption {\n\treturn func(d *DiamondDescriptor) {\n\t\td.Tag = tag\n\t}\n}", "func NewForkingDigesterMock(t minimock.Tester) *ForkingDigesterMock {\n\tm := &ForkingDigesterMock{t: t}\n\tif controller, ok := t.(minimock.MockController); ok {\n\t\tcontroller.RegisterMocker(m)\n\t}\n\n\tm.AddNextMock = mForkingDigesterMockAddNext{mock: m}\n\tm.AddNextMock.callArgs = []*ForkingDigesterMockAddNextParams{}\n\n\tm.FinishSequenceMock = mForkingDigesterMockFinishSequence{mock: m}\n\n\tm.ForkSequenceMock = mForkingDigesterMockForkSequence{mock: m}\n\n\tm.GetDigestMethodMock = mForkingDigesterMockGetDigestMethod{mock: m}\n\n\tm.GetDigestSizeMock = mForkingDigesterMockGetDigestSize{mock: m}\n\n\treturn m\n}", "func New() ID {\n\treturn dgen.New()\n}", "func New(\n\tdatabaseContext model.DBReader,\n\tdagTopologyManager model.DAGTopologyManager,\n\tghostdagDataStore model.GHOSTDAGDataStore,\n\theaderStore model.BlockHeaderStore,\n\tk model.KType) model.GHOSTDAGManager {\n\n\treturn &ghostdagHelper{\n\t\tdbAccess: databaseContext,\n\t\tdagTopologyManager: dagTopologyManager,\n\t\tdataStore: ghostdagDataStore,\n\t\theaderStore: headerStore,\n\t\tk: k,\n\t}\n}", "func NewIGD() (igd IGD, err error) {\n\tigd, err = NewUpnpIGD()\n\tif err != nil {\n\t\tlog.Debugf(\"Unable to initialize UPnP IGD, falling back to NAT-PMP: %s\", err)\n\t\tigd, err = NewNATPMPIGD()\n\t}\n\treturn\n}", "func newDHT(r *Router) *dht {\n\td := &dht{\n\t\tr: r,\n\t\tfinger: make(map[types.PublicKey]dhtEntry),\n\t}\n\treturn d\n}", "func New(pc chan []string) *Drawer {\n\td := Drawer{nil, nil, nil, nil}\n\td.list = ld.New(pc)\n\td.sparkline = sd.New(pc)\n\td.table = td.New(pc)\n\td.packetChannel = pc\n\n\treturn &d\n}", "func NewDigester(opts ...digester.Option) (*Digester, error) {\n\tropts := digester.Options{}\n\tfor _, apply := range opts {\n\t\tapply(&ropts)\n\t}\n\n\treturn &Digester{\n\t\topts: ropts,\n\t}, nil\n}", "func New() *deck.Deck {\n\tn := *d\n\treturn &n\n}", "func newHammer() *cobra.Command {\n\tvar cluster []string\n\tvar dbName string\n\tvar id int\n\tvar count int\n\n\tcmd := &cobra.Command{\n\t\tUse: \"hammer\",\n\t\tShort: \"load test the database.\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tfmt.Println(\"defaultLogLevel:\", defaultLogLevel)\n\t\t\tlogger := NewLogFunc(defaultLogLevel, \"hammy:: \", log.Writer())\n\t\t\tlogger(LogDebug, \"checking hammer logger\")\n\t\t\thammer(&globalKeys, id, count, logger, dbName, cluster...)\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tflags := cmd.Flags()\n\tflags.StringSliceVarP(&cluster, \"cluster\", \"c\", clusterList(), \"addresses of existing cluster nodes\")\n\tflags.StringVarP(&dbName, \"database\", \"d\", envy.StringDefault(\"DQLITED_DB\", defaultDatabase), \"name of database to use\")\n\tflags.IntVarP(&count, \"count\", \"n\", 10000, \"how many times to repeat\")\n\tflags.IntVarP(&id, \"id\", \"i\", envy.IntDefault(\"DQLITED_ID\", 1), \"server id\")\n\n\treturn cmd\n}", "func NewDn(value string) Dn {\n\tdn := Dn{\n\t\tValue: value,\n\t}\n\n\treturn dn\n}", "func (in *DiamondList) DeepCopy() *DiamondList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DiamondList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func NewDGraph(adjacencyList AdjacencyList) (*DGraph, error) {\n\tresult := new(DGraph)\n\tresult.Set = make(Set, len(adjacencyList))\n\n\t// two phases:\n\t//\n\t// Phase 1: create nodes for all the keys in the adjacencyList and\n\t// store them in result.nodes. They wont have any children yet.\n\tfor nodeKey, _ := range adjacencyList {\n\t\tresult.Add(&Node{\n\t\t\tKey: nodeKey,\n\t\t})\n\t}\n\n\t// Phase 2: go again over every key in the adjacencyList, adding\n\t// children to each node.\n\tfor parentKey, childrenKeys := range adjacencyList {\n\t\tparent, _ := result.Get(parentKey)\n\t\tparent.Children = make(Set, len(childrenKeys))\n\n\t\tfor _, k := range childrenKeys {\n\t\t\tchildren, ok := result.Get(k)\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"unknown children %s in node %s\",\n\t\t\t\t\tk, parentKey)\n\t\t\t}\n\n\t\t\tparent.Children.Add(children)\n\t\t}\n\t}\n\n\treturn result, nil\n}", "func NewDMG(path string, opts ...DMGOption) (*DMG, error) {\n\td := &DMG{\n\t\tdmgpath: path,\n\t\tlogger: log.New(os.Stderr, \"test\", 1),\n\t}\n\tfor _, opt := range opts {\n\t\topt(d)\n\t}\n\n\targs := []string{\"imageinfo\", d.dmgpath, \"-plist\"}\n\tout, err := exec.Command(\"/usr/bin/hdiutil\", args...).Output()\n\tdata := bytes.Replace(out, []byte(`<integer>-1</integer>`), []byte(`<string>-1</string>`), -1)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to get the info from dmg : %s\", err)\n\t}\n\tvar diskInfo BackingStoreInfo\n\terr = plist.Unmarshal(data, &diskInfo)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to read disk info: %s\", err)\n\t}\n\td.ImageInfo = diskInfo\n\treturn d, nil\n}", "func (f *Framework) NewDiagnosis(name, ns, nodeName, operationSet string) *diagnosisv1.Diagnosis {\n\n\treturn &diagnosisv1.Diagnosis{\n\t\tTypeMeta: metav1.TypeMeta{},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: fmt.Sprintf(\"%v-%v\", name, RandomSuffix()),\n\t\t\tNamespace: ns,\n\t\t\tLabels: map[string]string{\n\t\t\t\tf.SelectorKey: name,\n\t\t\t},\n\t\t},\n\t\tSpec: diagnosisv1.DiagnosisSpec{NodeName: nodeName, OperationSet: operationSet},\n\t\tStatus: diagnosisv1.DiagnosisStatus{},\n\t}\n}", "func DiamondExists(repo, diamondID string, stores context2.Stores) error {\n\texists, err := GetDiamondStore(stores).Has(context.Background(), model.GetArchivePathToInitialDiamond(repo, diamondID))\n\tif err != nil {\n\t\treturn errors.New(\"failed to retrieve diamond from store\").Wrap(err)\n\t}\n\tif !exists {\n\t\treturn errors.New(\"diamond validation\").WrapMessage(\"diamond %s doesn't exist for repo %s \", diamondID, repo)\n\t}\n\treturn nil\n}", "func NewDialedKlient(opts KlientOptions) (*Klient, error) {\n\tc, err := CreateKlientClient(opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := c.Dial(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewKlient(c), nil\n}", "func New() *Dqueue {\n\treturn &Dqueue{\n\t\tdqueue: &doublelinkedlist.DoubleLinkedList{},\n\t}\n}", "func NewDkgGroup(dishonestThreshold int, size int) *Group {\n\tmemberIDs := make([]MemberIndex, size)\n\tfor i := 0; i < size; i++ {\n\t\tmemberIDs[i] = MemberIndex(i + 1)\n\t}\n\n\treturn &Group{\n\t\tdishonestThreshold: dishonestThreshold,\n\t\tdisqualifiedMemberIDs: []MemberIndex{},\n\t\tinactiveMemberIDs: []MemberIndex{},\n\t\tmemberIDs: memberIDs,\n\t}\n}", "func NewGenerateTransportDgd(name string, gorillaMux bool, transport string, methods []string) Gen {\n\ti := &GenerateTransportDgd{\n\t\tname: name,\n\t\tgorillaMux: gorillaMux,\n\t\tinterfaceName: utils.ToCamelCase(name + \"Service\"),\n\t\tdestPath: fmt.Sprintf(viper.GetString(\"gk_service_path_format\"), utils.ToLowerSnakeCase2(name)),\n\t\tmethods: methods,\n\t}\n\ti.filePath = path.Join(i.destPath, viper.GetString(\"gk_service_file_name\"))\n\ti.transport = transport\n\t// Not used.\n\ti.srcFile = jen.NewFilePath(\"\")\n\ti.InitPg()\n\t//\n\ti.fs = fs.Get()\n\treturn i\n}", "func NewDfdd(context *Context, timeSource common.TimeSource) Dfdd {\n\tdfdd := &dfddImpl{\n\t\tcontext: context,\n\t\ttimeSource: timeSource,\n\t\tshutdownC: make(chan struct{}),\n\t\tinputListenerCh: make(chan *common.RingpopListenerEvent, listenerChannelSize),\n\t\tstoreListenerCh: make(chan *common.RingpopListenerEvent, listenerChannelSize),\n\t}\n\tdfdd.inputHosts.Store(make(map[string]dfddHost, 8))\n\tdfdd.storeHosts.Store(make(map[string]dfddHost, 8))\n\treturn dfdd\n}", "func NewContainerd() (*Containerd, error) {\n client := new(Containerd)\n\n Logger.Info(\"Connecting to containerd\")\n if c, err := containerd.New(ContainerdSocketPath); err != nil {\n return nil, err\n } else {\n Logger.Info(\"Connected to containerd as client\")\n client.Client = c\n }\n\n Logger.Info(\"Creating containerd client context\")\n client.Context = namespaces.WithNamespace(context.Background(),\n ContainerdNamespace)\n\n return client, nil\n}", "func DiamondMode(mode ConflictMode) DiamondDescriptorOption {\n\treturn func(d *DiamondDescriptor) {\n\t\td.Mode = mode\n\t}\n}", "func New(me protocol.PeerAddress, codec protocol.PeerAddressCodec, store kv.Table, bootstrapAddrs ...protocol.PeerAddress) (DHT, error) {\n\t// Validate input parameters\n\tif me == nil {\n\t\tpanic(\"pre-condition violation: self PeerAddress cannot be nil\")\n\t}\n\tif codec == nil {\n\t\tpanic(\"pre-condition violation: PeerAddressCodec cannot be nil\")\n\t}\n\n\t// Create a in-memory store if user doesn't provide one.\n\tif store == nil {\n\t\tstore = kv.NewTable(kv.NewMemDB(kv.GobCodec), \"dht\")\n\t}\n\n\tdht := &dht{\n\t\tme: me,\n\t\tcodec: codec,\n\t\tstore: store,\n\n\t\tgroupsMu: new(sync.RWMutex),\n\t\tgroups: map[protocol.GroupID]protocol.PeerIDs{},\n\n\t\tinMemCacheMu: new(sync.RWMutex),\n\t\tinMemCache: map[string]protocol.PeerAddress{},\n\t}\n\n\tif err := dht.fillInMemCache(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn dht, dht.addBootstrapNodes(bootstrapAddrs)\n}", "func TestTransactionGraphDiamond(t *testing.T) {\n\tif testing.Short() {\n\t\tt.SkipNow()\n\t}\n\t// Create a transaction pool tester.\n\ttpt, err := createTpoolTester(t.Name())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer tpt.Close()\n\n\t// Create a transaction sending money to an output that TransactionGraph can\n\t// spent (the empty UnlockConditions).\n\ttxns, err := tpt.wallet.SendSiacoins(types.SiacoinPrecision.Mul64(100), types.UnlockConditions{}.UnlockHash())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Get the output of that transaction.\n\tgraphSourceOutputID := txns[len(txns)-1].SiacoinOutputID(0)\n\tvar edges []types.TransactionGraphEdge\n\tsources := []int{0, 0, 1, 2}\n\tdests := []int{1, 2, 3, 3}\n\tvalues := []uint64{40, 40, 30, 30}\n\tfees := []uint64{10, 10, 10, 10}\n\tfor i := range sources {\n\t\tedges = append(edges, types.TransactionGraphEdge{\n\t\t\tDest: dests[i],\n\t\t\tFee: types.SiacoinPrecision.Mul64(fees[i]),\n\t\t\tSource: sources[i],\n\t\t\tValue: types.SiacoinPrecision.Mul64(values[i]),\n\t\t})\n\t}\n\tgraphTxns, err := types.TransactionGraph(graphSourceOutputID, edges)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif len(graphTxns) != 3 {\n\t\tt.Fatal(\"wrong number of tranasctions produced\")\n\t}\n\terr = tpt.tpool.AcceptTransactionSet(graphTxns)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func NewDaisyInflater(args ImportArguments, fileInspector imagefile.Inspector) (Inflater, error) {\n\tdiskName := \"disk-\" + args.ExecutionID\n\tvar wfPath string\n\tvar vars map[string]string\n\tvar inflationDiskIndex int\n\tif isImage(args.Source) {\n\t\twfPath = inflateImagePath\n\t\tvars = map[string]string{\n\t\t\t\"source_image\": args.Source.Path(),\n\t\t\t\"disk_name\": diskName,\n\t\t}\n\t\tinflationDiskIndex = 0 // Workflow only uses one disk.\n\t} else {\n\t\twfPath = inflateFilePath\n\t\tvars = createDaisyVarsForFile(args, fileInspector, diskName)\n\t\tinflationDiskIndex = 1 // First disk is for the worker\n\t}\n\n\twf, err := daisycommon.ParseWorkflow(path.Join(args.WorkflowDir, wfPath), vars,\n\t\targs.Project, args.Zone, args.ScratchBucketGcsPath, args.Oauth, args.Timeout.String(), args.ComputeEndpoint,\n\t\targs.GcsLogsDisabled, args.CloudLogsDisabled, args.StdoutLogsDisabled)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor k, v := range vars {\n\t\twf.AddVar(k, v)\n\t}\n\n\tdaisyUtils.UpdateAllInstanceNoExternalIP(wf, args.NoExternalIP)\n\tif args.UefiCompatible {\n\t\taddFeatureToDisk(wf, \"UEFI_COMPATIBLE\", inflationDiskIndex)\n\t}\n\tif strings.Contains(args.OS, \"windows\") {\n\t\taddFeatureToDisk(wf, \"WINDOWS\", inflationDiskIndex)\n\t}\n\n\t// Temporary fix to ensure gcloud shows daisy's output.\n\t// A less fragile approach is tracked in b/161567644.\n\twf.Name = LogPrefix\n\treturn &daisyInflater{\n\t\twf: wf,\n\t\tinflatedDiskURI: fmt.Sprintf(\"zones/%s/disks/%s\", args.Zone, diskName),\n\t}, nil\n}", "func NewHdd() *Hdd {\n\tthis := Hdd{}\n\treturn &this\n}", "func (g Generator) NewDoctor(c *pathway.Consultant) *ir.Doctor {\n\tif c == nil {\n\t\treturn g.doctors.GetRandomDoctor()\n\t}\n\tif doctor := g.doctors.GetByID(*c.ID); doctor != nil {\n\t\treturn doctor\n\t}\n\tnewDoctor := &ir.Doctor{\n\t\t// A valid pathway.Consultant has all the fields set, so we can just dereference.\n\t\tID: *c.ID,\n\t\tSurname: *c.Surname,\n\t\tPrefix: *c.Prefix,\n\t\tFirstName: *c.FirstName,\n\t\tSpecialty: g.messageConfig.HospitalService,\n\t}\n\tg.doctors.Add(newDoctor)\n\treturn newDoctor\n}", "func MockDiamondWorkflow(hd *hood.Hood) *Workflow {\n\tworkflow := MockWorkflow(hd)\n\tj1 := MockProtojob(hd, workflow)\n\tj2 := MockProtojob(hd, workflow)\n\tj3 := MockProtojob(hd, workflow)\n\tj4 := MockProtojob(hd, workflow)\n\te1 := MockWorkflowEdge(hd, j1, j2)\n\te2 := MockWorkflowEdge(hd, j1, j3)\n\te3 := MockWorkflowEdge(hd, j2, j4)\n\te4 := MockWorkflowEdge(hd, j3, j4)\n\n\tworkflowBatch := MockWorkflowBatch(hd, workflow)\n\trdd1 := MockRdd(hd, workflowBatch, j1)\n\trdd2 := MockRdd(hd, workflowBatch, j2)\n\trdd3 := MockRdd(hd, workflowBatch, j3)\n\trdd4 := MockRdd(hd, workflowBatch, j4)\n\tMockRddEdge(hd, rdd1, rdd2, e1)\n\tMockRddEdge(hd, rdd1, rdd3, e2)\n\tMockRddEdge(hd, rdd2, rdd4, e3)\n\tMockRddEdge(hd, rdd3, rdd4, e4)\n\n\tw1 := MockWorker(hd)\n\tw2 := MockWorker(hd)\n\n\t// Place a segment for every rdd on every worker\n\trdds := []*Rdd{rdd1, rdd2, rdd3, rdd4}\n\tworkers := []*Worker{w1, w2}\n\tfor _, rdd := range rdds {\n\t\tfor _, worker := range workers {\n\t\t\tMockSegment(hd, rdd, worker)\n\t\t}\n\t}\n\n\treturn workflow\n}", "func New(hasher func(v interface{}) uint32) *Dtrie {\n\tif hasher == nil {\n\t\thasher = defaultHasher\n\t}\n\treturn &Dtrie{\n\t\troot: emptyNode(0, 32),\n\t\thasher: hasher,\n\t}\n}", "func NewDijkstra(g *graph, s, t int) *Dijkstra {\n\treturn &Dijkstra{\n\t\tgraph: g,\n\t\tsource: s,\n\t\ttarget: t,\n\t\tfrontier: make(map[int]graphEdge),\n\t\tcost: make(map[int]float32),\n\t\tspt: make(map[int]graphEdge),\n\t}\n}", "func NewClientD(server string) pb.GPNSClient {\n\tconn, err := grpc.Dial(server, grpc.WithInsecure())\n\tif err != nil {\n\t\tlog.Fatal(\"connect to domestic rpc server failed\")\n\t}\n\tgo receiveChat()\n\treturn pb.NewGPNSClient(conn)\n}", "func newCommandDisconn(cli *client.Client) command {\n\treturn &commandDisconn{\n\t\tcli: cli,\n\t}\n}", "func NewDaddy() *Daddy {\n\treturn &Daddy{\n\t\tSon: make(map[string]*Assassin),\n\t\tSibling: make(map[string]*Sibling),\n\t}\n}", "func New(duration time.Duration) *Dam {\n\td := &Dam{\n\t\tstorage: make(map[string]*element),\n\t\ttickerDone: make(chan struct{}),\n\t}\n\tif duration > time.Duration(0) {\n\t\td.ticker = time.NewTicker(duration)\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-d.ticker.C:\n\t\t\t\t\td.Purge()\n\t\t\t\tcase <-d.tickerDone:\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\treturn d\n}", "func NewDelegation(d *types.Delegation) *Delegation {\n\treturn &Delegation{Delegation: *d, cg: new(singleflight.Group)}\n}", "func (mdhdBoxFactory) New(box bmfcommon.Box) (cb bmfcommon.CommonBox, childBoxSeriesOffset int, err error) {\n\tdefer func() {\n\t\tif errRaw := recover(); errRaw != nil {\n\t\t\terr = log.Wrap(errRaw.(error))\n\t\t}\n\t}()\n\n\tmdhdBox := &MdhdBox{\n\t\tBox: box,\n\t}\n\n\terr = mdhdBox.parse()\n\tlog.PanicIf(err)\n\n\treturn mdhdBox, -1, nil\n}", "func NewKingdom(name string, emblem string) *kingdom {\n\treturn &kingdom{Name: name, Emblem: emblem}\n}", "func (d *devicelib) NewMigDeviceByUUID(uuid string) (MigDevice, error) {\n\tdev, ret := d.nvml.DeviceGetHandleByUUID(uuid)\n\tif ret != nvml.SUCCESS {\n\t\treturn nil, fmt.Errorf(\"error getting device handle for uuid '%v': %v\", uuid, ret)\n\t}\n\treturn d.NewMigDevice(dev)\n}", "func NewDefaultDialedKlient() (*Klient, error) {\n\treturn NewDialedKlient(NewKlientOptions())\n}", "func NewDfdd(context *Context) Dfdd {\n\treturn &dfddImpl{\n\t\tcontext: context,\n\t\tshutdownC: make(chan struct{}),\n\t\tinputListenerCh: make(chan *common.RingpopListenerEvent, listenerChannelSize),\n\t\tstoreListenerCh: make(chan *common.RingpopListenerEvent, listenerChannelSize),\n\t\tunhealthyStores: make(map[string]time.Time),\n\t\tunhealthyInputs: make(map[string]time.Time),\n\t\thostDownPeriodForStage2: hostDownPeriodForStage2,\n\t\thealthCheckInterval: healthCheckInterval,\n\t}\n}", "func DbGetPKIDsThatDiamondedYouMap(handle *badger.DB, yourPKID *PKID, fetchYouDiamonded bool) (\n\t_pkidToDiamondsMap map[PKID][]*DiamondEntry, _err error) {\n\n\tprefix := _dbSeekPrefixForPKIDsThatDiamondedYou(yourPKID)\n\tdiamondSenderStartIdx := 1 + btcec.PubKeyBytesLenCompressed\n\tdiamondSenderEndIdx := 1 + 2*btcec.PubKeyBytesLenCompressed\n\tdiamondReceiverStartIdx := 1\n\tdiamondReceiverEndIdx := 1 + btcec.PubKeyBytesLenCompressed\n\tif fetchYouDiamonded {\n\t\tprefix = _dbSeekPrefixForPKIDsThatYouDiamonded(yourPKID)\n\t\tdiamondSenderStartIdx = 1\n\t\tdiamondSenderEndIdx = 1 + btcec.PubKeyBytesLenCompressed\n\t\tdiamondReceiverStartIdx = 1 + btcec.PubKeyBytesLenCompressed\n\t\tdiamondReceiverEndIdx = 1 + 2*btcec.PubKeyBytesLenCompressed\n\t}\n\tkeysFound, valsFound := _enumerateKeysForPrefix(handle, prefix)\n\n\tpkidsToDiamondEntryMap := make(map[PKID][]*DiamondEntry)\n\tfor ii, keyBytes := range keysFound {\n\t\t// The DiamondEntry found must not be nil.\n\t\tdiamondEntry := _DbDiamondEntryForDbBuf(valsFound[ii])\n\t\tif diamondEntry == nil {\n\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\"DbGetPKIDsThatDiamondedYouMap: Found nil DiamondEntry for public key %v \"+\n\t\t\t\t\t\"and key bytes %#v when seeking; this should never happen\",\n\t\t\t\tPkToStringMainnet(yourPKID[:]), keyBytes)\n\t\t}\n\t\texpectedDiamondKeyLen := 1 + 2*btcec.PubKeyBytesLenCompressed + HashSizeBytes\n\t\tif len(keyBytes) != expectedDiamondKeyLen {\n\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\"DbGetPKIDsThatDiamondedYouMap: Invalid key length %v should be %v\",\n\t\t\t\tlen(keyBytes), expectedDiamondKeyLen)\n\t\t}\n\n\t\t// Note: The code below is mainly just sanity-checking. Checking the key isn't actually\n\t\t// needed in this function, since all the information is duplicated in the entry.\n\n\t\t// Chop out the diamond sender PKID.\n\t\tdiamondSenderPKIDBytes := keyBytes[diamondSenderStartIdx:diamondSenderEndIdx]\n\t\tdiamondSenderPKID := &PKID{}\n\t\tcopy(diamondSenderPKID[:], diamondSenderPKIDBytes)\n\t\t// It must match what's in the DiamondEntry\n\t\tif !reflect.DeepEqual(diamondSenderPKID, diamondEntry.SenderPKID) {\n\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\"DbGetPKIDsThatDiamondedYouMap: Sender PKID in DB %v did not \"+\n\t\t\t\t\t\"match Sender PKID in DiamondEntry %v; this should never happen\",\n\t\t\t\tPkToStringBoth(diamondSenderPKID[:]), PkToStringBoth(diamondEntry.SenderPKID[:]))\n\t\t}\n\n\t\t// Chop out the diamond receiver PKID\n\t\tdiamondReceiverPKIDBytes := keyBytes[diamondReceiverStartIdx:diamondReceiverEndIdx]\n\t\tdiamondReceiverPKID := &PKID{}\n\t\tcopy(diamondReceiverPKID[:], diamondReceiverPKIDBytes)\n\t\t// It must match what's in the DiamondEntry\n\t\tif !reflect.DeepEqual(diamondReceiverPKID, diamondEntry.ReceiverPKID) {\n\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\"DbGetPKIDsThatDiamondedYouMap: Receiver PKID in DB %v did not \"+\n\t\t\t\t\t\"match Receiver PKID in DiamondEntry %v; this should never happen\",\n\t\t\t\tPkToStringBoth(diamondReceiverPKID[:]), PkToStringBoth(diamondEntry.ReceiverPKID[:]))\n\t\t}\n\n\t\t// Chop out the diamond post hash.\n\t\tdiamondPostHashBytes := keyBytes[1+2*btcec.PubKeyBytesLenCompressed:]\n\t\tdiamondPostHash := &BlockHash{}\n\t\tcopy(diamondPostHash[:], diamondPostHashBytes)\n\t\t// It must match what's in the entry\n\t\tif *diamondPostHash != *diamondEntry.DiamondPostHash {\n\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\"DbGetPKIDsThatDiamondedYouMap: Post hash found in DB key %v \"+\n\t\t\t\t\t\"did not match post hash in DiamondEntry %v; this should never happen\",\n\t\t\t\tdiamondPostHash, diamondEntry.DiamondPostHash)\n\t\t}\n\n\t\t// If a map entry doesn't exist for this sender, create one.\n\t\tnewListOfEntrys := pkidsToDiamondEntryMap[*diamondSenderPKID]\n\t\tnewListOfEntrys = append(newListOfEntrys, diamondEntry)\n\t\tpkidsToDiamondEntryMap[*diamondSenderPKID] = newListOfEntrys\n\t}\n\n\treturn pkidsToDiamondEntryMap, nil\n}", "func New(\n\tdatabaseContext model.DBReader,\n\tdagTopologyManager model.DAGTopologyManager,\n\tghostdagDataStore model.GHOSTDAGDataStore,\n\theaderStore model.BlockHeaderStore,\n\tk externalapi.KType,\n\tgenesisHash *externalapi.DomainHash) model.GHOSTDAGManager {\n\n\treturn &ghostdagManager{\n\t\tdatabaseContext: databaseContext,\n\t\tdagTopologyManager: dagTopologyManager,\n\t\tghostdagDataStore: ghostdagDataStore,\n\t\theaderStore: headerStore,\n\t\tk: k,\n\t\tgenesisHash: genesisHash,\n\t}\n}", "func New() (*Containerd, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)\n\tdefer cancel()\n\n\tconn, err := grpc.DialContext(ctx, defaultContainerdAddress, grpc.WithInsecure(), grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(1024*1024*16)), grpc.WithContextDialer(func(ctx context.Context, addr string) (net.Conn, error) {\n\t\treturn (&net.Dialer{}).DialContext(ctx, \"unix\", addr)\n\t}))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Containerd{\n\t\tconn: conn,\n\t}, nil\n}", "func New(configurator PackageConfigurator, store ScriptPersister) *Ankiddie {\n\tankiddie := &Ankiddie{\n\t\tenvs: make(map[uint]*Environment),\n\t\tstore: store,\n\t}\n\n\t// TODO because of how anko works, this will actually mess with the packages\n\t// for all envs on all Ankiddies, and not just this one\n\tif configurator != nil {\n\t\tconfigurator.ConfigurePackages(env.Packages, env.PackageTypes)\n\t}\n\treturn ankiddie\n}", "func NewDirectedGraph() *DirectedGraph {\n\treturn &DirectedGraph{make(map[string]value)}\n}", "func GenTxOutfeeQuantityDiamondTransfer(ctx ctx.Context, params []string) {\n\tif len(params) < 5 {\n\t\tfmt.Println(\"params not enough\")\n\t\treturn\n\t}\n\n\tfromAddressArgv := params[0]\n\ttoAddressArgv := params[1]\n\tdiamondsArgv := params[2]\n\tfeeAddressArgv := params[3]\n\tfeeArgv := params[4]\n\n\t// Check field\n\tdiamonds := strings.Split(diamondsArgv, \",\")\n\tif len(diamonds) > 200 {\n\t\tfmt.Printf(\"diamonds number is too much.\\n\")\n\t\treturn\n\t}\n\n\tfor _, diamond := range diamonds {\n\t\t_, dddok := x16rs.IsDiamondHashResultString(\"0000000000\" + diamond)\n\t\tif !dddok {\n\t\t\tfmt.Printf(\"%s is not diamond value.\\n\", diamond)\n\t\t\treturn\n\t\t}\n\t}\n\n\tfromaddress := ctx.IsInvalidAccountAddress(fromAddressArgv)\n\tif fromaddress == nil {\n\t\treturn\n\t}\n\n\ttoaddress := ctx.IsInvalidAccountAddress(toAddressArgv)\n\tif toaddress == nil {\n\t\treturn\n\t}\n\n\tfeeAddress := ctx.IsInvalidAccountAddress(feeAddressArgv)\n\tif feeAddress == nil {\n\t\treturn\n\t}\n\n\tfeeAmount := ctx.IsInvalidAmountString(feeArgv)\n\tif feeAmount == nil {\n\t\treturn\n\t}\n\n\t// Create action\n\tvar dimtransfer actions.Action_6_OutfeeQuantityDiamondTransfer\n\tdimtransfer.FromAddress = *fromaddress\n\tdimtransfer.ToAddress = *toaddress\n\tdimtransfer.DiamondList.Count = fields.VarUint1(len(diamonds))\n\tdimtransfer.DiamondList.Diamonds = make([]fields.DiamondName, len(diamonds))\n\tfor i, v := range diamonds {\n\t\tdimtransfer.DiamondList.Diamonds[i] = fields.DiamondName(v)\n\t}\n\n\t// Create transaction\n\tnewTrs, e5 := transactions.NewEmptyTransaction_2_Simple(*feeAddress)\n\tnewTrs.Timestamp = fields.BlockTxTimestamp(ctx.UseTimestamp()) // Use the timestamp of hold\n\tif e5 != nil {\n\t\tfmt.Println(\"create transaction error, \" + e5.Error())\n\t\treturn\n\t}\n\tnewTrs.Fee = *feeAmount // set fee\n\n\t// Put in action\n\tnewTrs.AppendAction(&dimtransfer)\n\n\t// sign\n\te6 := newTrs.FillNeedSigns(ctx.GetAllPrivateKeyBytes(), nil)\n\tif e6 != nil {\n\t\tfmt.Println(\"sign transaction error, \" + e6.Error())\n\t\treturn\n\t}\n\n\t// Check signature\n\tsigok, sigerr := newTrs.VerifyAllNeedSigns()\n\tif sigerr != nil || !sigok {\n\t\tfmt.Println(\"transaction VerifyAllNeedSigns fail\")\n\t\treturn\n\t}\n\n\t// Datalization\n\tbodybytes, e7 := newTrs.Serialize()\n\tif e7 != nil {\n\t\tfmt.Println(\"transaction serialize error, \" + e7.Error())\n\t\treturn\n\t}\n\n\t// ok\n\tctx.Println(\"transaction create success! \")\n\tctx.Println(\"hash: <\" + hex.EncodeToString(newTrs.Hash()) + \">, hash_with_fee: <\" + hex.EncodeToString(newTrs.HashWithFee()) + \">\")\n\tctx.Println(\"body length \" + strconv.Itoa(len(bodybytes)) + \" bytes, hex body is:\")\n\tctx.Println(\"-------- TRANSACTION BODY START --------\")\n\tctx.Println(hex.EncodeToString(bodybytes))\n\tctx.Println(\"-------- TRANSACTION BODY END --------\")\n\n\t// record\n\tctx.SetTxToRecord(newTrs.Hash(), newTrs)\n}", "func New() *d.Client {\n\tvar err error\n\tif os.Getenv(\"DOCKER_HOST\") != \"\" {\n\t\tclient, err = d.NewClient(os.Getenv(\"DOCKER_HOST\"))\n\t} else {\n\t\tclient, err = d.NewClient(\"DEFAULTHERE\")\n\t}\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn nil\n\t}\n\n\treturn client\n}", "func createDog() *Dog {\n\treturn NewDog(\"Hachi\")\n}", "func NewDistKeeper(d float64) *DistKeeper { return &DistKeeper{Heap{{Dist: d}}} }", "func NewDiscovery(hwaddr net.HardwareAddr, modifiers ...Modifier) (*DHCPv4, error) {\n\treturn New(PrependModifiers(modifiers,\n\t\tWithHwAddr(hwaddr),\n\t\tWithRequestedOptions(\n\t\t\tOptionSubnetMask,\n\t\t\tOptionRouter,\n\t\t\tOptionDomainName,\n\t\t\tOptionDomainNameServer,\n\t\t),\n\t\tWithMessageType(MessageTypeDiscover),\n\t)...)\n}", "func NewDHT(store Store, options *Options) (*DHT, error) {\n\t// validate the options, if it's invalid, set them to default value\n\tif options.IP == \"\" {\n\t\toptions.IP = defaultNetworkAddr\n\t}\n\tif options.Port <= 0 {\n\t\toptions.Port = defaultNetworkPort\n\t}\n\n\ts := &DHT{\n\t\tstore: store,\n\t\toptions: options,\n\t\tdone: make(chan struct{}),\n\t}\n\t// new a hashtable with options\n\tht, err := NewHashTable(options)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"new hashtable: %v\", err)\n\t}\n\ts.ht = ht\n\n\t// new network service for dht\n\tnetwork, err := NewNetwork(s, ht.self)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"new network: %v\", err)\n\t}\n\ts.network = network\n\n\treturn s, nil\n}", "func newDupper() *dupper {\n\treturn &dupper{\n\t\tdts: make(map[string]*UserTypeDefinition),\n\t\tdmts: make(map[string]*MediaTypeDefinition),\n\t}\n}", "func NewDig(licenseID int32, posX int32, posY int32, depth int32) *Dig {\n\tthis := Dig{}\n\tthis.LicenseID = licenseID\n\tthis.PosX = posX\n\tthis.PosY = posY\n\tthis.Depth = depth\n\treturn &this\n}", "func NewGateway(c GatewayConfig, d *Daemon) *Gateway {\n\treturn &Gateway{\n\t\tConfig: c,\n\t\td: d,\n\t\tv: d.visor,\n\t\trequests: make(chan strand.Request, c.BufferSize),\n\t\tquit: make(chan struct{}),\n\t}\n}", "func New(node string, receivePort uint16, bits uint64) (*DHT, error) { // configuration\n\tcaller, err := chord.NewNodeCaller(receivePort)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &DHT{\n\t\tnode: node,\n\t\tbits: bits,\n\t\tcaller: caller,\n\t}, nil\n}", "func NewDefaultPlusDi() (indicator *PlusDi, err error) {\n\ttimePeriod := 14\n\treturn NewPlusDi(timePeriod)\n}", "func NewDClient(stdClient *http.Client, username string, password string) *DClient {\n\treturn &DClient{\n\t\tclient: stdClient,\n\t\tusername: username,\n\t\tpassword: password,\n\t}\n}", "func NewDenom(id, name, schema string, creator sdk.AccAddress) Denom {\n\treturn Denom{\n\t\tId: id,\n\t\tName: name,\n\t\tSchema: schema,\n\t\tCreator: creator.String(),\n\t}\n}", "func NewXDG() (*XDG, error) {\n\trv := &XDG{}\n\n\tdataHome, err := parseDataHome()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trv.dataHome = dataHome\n\trv.dataDirs = parseDataDirs()\n\n\treturn rv, nil\n}", "func NewDeposit(ctx *middleware.Context, handler DepositHandler) *Deposit {\n\treturn &Deposit{Context: ctx, Handler: handler}\n}", "func NewDeleteSingleBeadSimulationDefault(code int) *DeleteSingleBeadSimulationDefault {\n\treturn &DeleteSingleBeadSimulationDefault{\n\t\t_statusCode: code,\n\t}\n}", "func NewDataWare() Dataware {\n\tconf := config.MyConfig()\n\tif conf.Develop.DatawareFake {\n\t\tlogrus.Info(\"in dataware fake mode so use faked dataware\")\n\t\treturn newDwFake()\n\t}\n\n\tinitGorm()\n\tdialect, dsn := conf.Database.Dsn()\n\tdb, err := gorm.Open(dialect, dsn)\n\tif err != nil {\n\t\tlogrus.Fatal(err)\n\t}\n\tinitDB(db)\n\tlogrus.Infof(\"connect database(%s) by dsn: %s\", dialect, dsn)\n\n\treturn newDwGorm(db)\n}", "func New(modifiers ...Modifier) (*DHCPv4, error) {\n\txid, err := GenerateTransactionID()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\td := DHCPv4{\n\t\tOpCode: OpcodeBootRequest,\n\t\tHWType: iana.HWTypeEthernet,\n\t\tClientHWAddr: make(net.HardwareAddr, 6),\n\t\tHopCount: 0,\n\t\tTransactionID: xid,\n\t\tNumSeconds: 0,\n\t\tFlags: 0,\n\t\tClientIPAddr: net.IPv4zero,\n\t\tYourIPAddr: net.IPv4zero,\n\t\tServerIPAddr: net.IPv4zero,\n\t\tGatewayIPAddr: net.IPv4zero,\n\t\tOptions: make(Options),\n\t}\n\tfor _, mod := range modifiers {\n\t\tmod(&d)\n\t}\n\treturn &d, nil\n}", "func NewDefragCommand() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"defrag\",\n\t\tShort: \"Defragments the storage of the etcd\",\n\t\tRun: defragCommandFunc,\n\t}\n\tcmd.Flags().StringVar(&defragDataDir, \"data-dir\", \"\", \"Required. Defragments a data directory not in use by etcd.\")\n\tcmd.MarkFlagRequired(\"data-dir\")\n\tcmd.MarkFlagDirname(\"data-dir\")\n\treturn cmd\n}", "func NewDC() Defector {\n\tonce.Do(func() {\n\t\tinstance = new(Defects)\n\t\tinstance.coll = make([]*Defect, 0)\n\t\tinstance.enabled = true\n\t\tinstance.Headers = []string{\n\t\t\t\"Column\",\n\t\t\t\"Row\",\n\t\t\t\"Message\",\n\t\t}\n\t})\n\treturn instance\n}", "func NewHydra(ctx context.Context, options Options) (*Hydra, error) {\n\tif options.Name != \"\" {\n\t\tnctx, err := tag.New(ctx, tag.Insert(metrics.KeyName, options.Name))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tctx = nctx\n\t}\n\n\tvar ds datastore.Batching\n\tvar err error\n\tif strings.HasPrefix(options.DatastorePath, \"postgresql://\") {\n\t\tfmt.Fprintf(os.Stderr, \"🐘 Using PostgreSQL datastore\\n\")\n\t\tds, err = hyds.NewPostgreSQLDatastore(ctx, options.DatastorePath, !options.DisableDBCreate)\n\t} else if strings.HasPrefix(options.DatastorePath, \"dynamodb://\") {\n\t\toptsStr := strings.TrimPrefix(options.DatastorePath, \"dynamodb://\")\n\t\ttable, err := parseDDBTable(optsStr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfmt.Fprintf(os.Stderr, \"Using DynamoDB datastore with table '%s'\\n\", table)\n\t\tddbClient := ddbv1.New(session.Must(session.NewSession()))\n\t\tddbDS := ddbds.New(ddbClient, table, ddbds.WithScanParallelism(5))\n\t\tds = ddbDS\n\t\tperiodictasks.RunTasks(ctx, []periodictasks.PeriodicTask{metricstasks.NewIPNSRecordsTask(ddbDS, ipnsRecordsTaskInterval)})\n\t} else {\n\t\tfmt.Fprintf(os.Stderr, \"🥞 Using LevelDB datastore\\n\")\n\t\tds, err = leveldb.NewDatastore(options.DatastorePath, nil)\n\t}\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create datastore: %w\", err)\n\t}\n\n\tvar hds []*head.Head\n\n\tif options.PeerstorePath == \"\" {\n\t\tfmt.Fprintf(os.Stderr, \"💭 Using in-memory peerstore\\n\")\n\t} else {\n\t\tfmt.Fprintf(os.Stderr, \"🥞 Using LevelDB peerstore (EXPERIMENTAL)\\n\")\n\t}\n\n\tif options.IDGenerator == nil {\n\t\toptions.IDGenerator = idgen.HydraIdentityGenerator\n\t}\n\tfmt.Fprintf(os.Stderr, \"🐲 Spawning %d heads: \\n\", options.NHeads)\n\n\tvar hyperLock sync.Mutex\n\thyperlog := hyperloglog.New()\n\n\t// What is a limiter?\n\tlimiter := make(chan struct{}, options.BsCon)\n\n\t// Increase per-host connection pool since we are making lots of concurrent requests to a small number of hosts.\n\ttransport := http.DefaultTransport.(*http.Transport).Clone()\n\ttransport.MaxIdleConns = 500\n\ttransport.MaxIdleConnsPerHost = 100\n\tlimitedTransport := &client.ResponseBodyLimitedTransport{RoundTripper: transport, LimitBytes: 1 << 20}\n\n\tdelegateHTTPClient := &http.Client{\n\t\tTimeout: options.DelegateTimeout,\n\t\tTransport: limitedTransport,\n\t}\n\n\tproviderStoreBuilder, err := newProviderStoreBuilder(ctx, delegateHTTPClient, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tprovidersFinder := hproviders.NewAsyncProvidersFinder(5*time.Second, 1000, 1*time.Hour)\n\tprovidersFinder.Run(ctx, 1000)\n\n\t// Reuse the HTTP client across all the heads.\n\tfor i := 0; i < options.NHeads; i++ {\n\t\ttime.Sleep(options.Stagger)\n\t\tfmt.Fprintf(os.Stderr, \".\")\n\n\t\tport := options.GetPort()\n\t\ttcpAddr, _ := multiaddr.NewMultiaddr(fmt.Sprintf(\"/ip4/0.0.0.0/tcp/%d\", port))\n\t\tquicAddr, _ := multiaddr.NewMultiaddr(fmt.Sprintf(\"/ip4/0.0.0.0/udp/%d/quic\", port))\n\t\tpriv, err := options.IDGenerator.AddBalanced()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to generate balanced private key %w\", err)\n\t\t}\n\t\thdOpts := []opts.Option{\n\t\t\topts.Datastore(ds),\n\t\t\topts.ProviderStoreBuilder(providerStoreBuilder),\n\t\t\topts.Addrs([]multiaddr.Multiaddr{tcpAddr, quicAddr}),\n\t\t\topts.ProtocolPrefix(options.ProtocolPrefix),\n\t\t\topts.BucketSize(options.BucketSize),\n\t\t\topts.Limiter(limiter),\n\t\t\topts.ID(priv),\n\t\t\topts.BootstrapPeers(options.BootstrapPeers),\n\t\t\topts.DelegateHTTPClient(delegateHTTPClient),\n\t\t\topts.DisableResourceManager(options.DisableResourceManager),\n\t\t\topts.ResourceManagerLimitsFile(options.ResourceManagerLimitsFile),\n\t\t\topts.ConnMgrHighWater(options.ConnMgrHighWater),\n\t\t\topts.ConnMgrLowWater(options.ConnMgrLowWater),\n\t\t\topts.ConnMgrGracePeriod(options.ConnMgrGracePeriod),\n\t\t}\n\t\tif options.EnableRelay {\n\t\t\thdOpts = append(hdOpts, opts.EnableRelay())\n\t\t}\n\t\tif options.DisableProviders {\n\t\t\thdOpts = append(hdOpts, opts.DisableProviders())\n\t\t}\n\t\tif options.DisableValues {\n\t\t\thdOpts = append(hdOpts, opts.DisableValues())\n\t\t}\n\t\tif options.DisableProvGC || i > 0 {\n\t\t\t// the first head GCs, if it's enabled\n\t\t\thdOpts = append(hdOpts, opts.DisableProvGC())\n\t\t}\n\t\tif options.DisableProvCounts || i > 0 {\n\t\t\t// the first head counts providers, if it's enabled\n\t\t\thdOpts = append(hdOpts, opts.DisableProvCounts())\n\t\t}\n\t\tif !options.DisablePrefetch {\n\t\t\thdOpts = append(hdOpts, opts.ProvidersFinder(providersFinder))\n\t\t}\n\t\tif options.PeerstorePath != \"\" {\n\t\t\tpstoreDs, err := leveldb.NewDatastore(fmt.Sprintf(\"%s/head-%d\", options.PeerstorePath, i), nil)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"failed to create peerstore datastore: %w\", err)\n\t\t\t}\n\t\t\tpstore, err := pstoreds.NewPeerstore(ctx, pstoreDs, pstoreds.DefaultOpts())\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"failed to create peerstore: %w\", err)\n\t\t\t}\n\t\t\thdOpts = append(hdOpts, opts.Peerstore(pstore))\n\t\t}\n\n\t\thd, bsCh, err := head.NewHead(ctx, hdOpts...)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to spawn node with swarm addresses %v %v: %w\", tcpAddr, quicAddr, err)\n\t\t}\n\n\t\thdCtx, err := tag.New(ctx, tag.Insert(metrics.KeyPeerID, hd.Host.ID().String()))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tstats.Record(hdCtx, metrics.Heads.M(1))\n\n\t\thd.Host.Network().Notify(&network.NotifyBundle{\n\t\t\tConnectedF: func(n network.Network, v network.Conn) {\n\t\t\t\thyperLock.Lock()\n\t\t\t\thyperlog.Insert([]byte(v.RemotePeer()))\n\t\t\t\thyperLock.Unlock()\n\t\t\t\tstats.Record(hdCtx, metrics.ConnectedPeers.M(1))\n\t\t\t},\n\t\t\tDisconnectedF: func(n network.Network, v network.Conn) {\n\t\t\t\tstats.Record(hdCtx, metrics.ConnectedPeers.M(-1))\n\t\t\t},\n\t\t})\n\n\t\tgo handleBootstrapStatus(hdCtx, bsCh)\n\n\t\thds = append(hds, hd)\n\t}\n\tfmt.Fprintf(os.Stderr, \"\\n\")\n\n\tfor _, hd := range hds {\n\t\tfmt.Fprintf(os.Stderr, \"🆔 %v\\n\", hd.Host.ID())\n\t\tfor _, addr := range hd.Host.Addrs() {\n\t\t\tfmt.Fprintf(os.Stderr, \"🐝 Swarm listening on %v\\n\", addr)\n\t\t}\n\t}\n\n\thydra := Hydra{\n\t\tHeads: hds,\n\t\tSharedDatastore: ds,\n\t\thyperLock: &hyperLock,\n\t\thyperlog: hyperlog,\n\t}\n\n\ttasks := []periodictasks.PeriodicTask{\n\t\tmetricstasks.NewRoutingTableSizeTask(hydra.GetRoutingTableSize, routingTableSizeTaskInterval),\n\t\tmetricstasks.NewUniquePeersTask(hydra.GetUniquePeersCount, uniquePeersTaskInterval),\n\t}\n\n\tperiodictasks.RunTasks(ctx, tasks)\n\n\treturn &hydra, nil\n}", "func NewDHTDistributor(cfg *DHTDistributorConfig, dClient *docker.Client) (*DefaultDistributor, error) {\n\tmu := &sync.Mutex{}\n\tactive := make(map[string]*torrent.Torrent)\n\n\tdist := &DefaultDistributor{\n\t\tcfg: cfg,\n\t\tdClient: dClient,\n\t\tmutex: mu,\n\t\tactive: active,\n\t}\n\n\t// preparing torrent client\n\ttc, err := dist.getTorrentClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdist.tClinet = tc\n\treturn dist, nil\n}", "func (d *ActivityDiagram) Decide() *shape.Diamond {\n\tnext := shape.NewDecision()\n\tadj := d.Diagram.Place(next)\n\tadj.Below(d.last, d.Spacing+next.Height()/2)\n\td.VAlignCenter(d.last, next)\n\td.Link(d.last, next)\n\td.last = next\n\treturn next\n}", "func New(ctx context.Context) (*CrosDisks, error) {\n\tconn, obj, err := dbusutil.Connect(ctx, dbusName, dbusPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &CrosDisks{conn, obj}, nil\n}", "func NewDump(d MyDB, inputDir string, jobs int) Dump {\n\tdumpDir := filepath.Join(inputDir, \"gni-dump\")\n\tdmp := Dump{InputDir: inputDir, DumpDir: dumpDir, JobsNum: jobs}\n\tdmp.DB = d.NewDb()\n\treturn dmp\n}", "func NewDentistClient(c config) *DentistClient {\n\treturn &DentistClient{config: c}\n}", "func GetDiamondStore(stores context2.Stores) storage.Store {\n\treturn getVMetaStore(stores)\n}", "func NewAdder(ctx context.Context, p pin.Pinner, bs bstore.GCLocker, ds ipld.DAGService) (*Adder, error) {\n\tbufferedDS := ipld.NewBufferedDAG(ctx, ds)\n\n\treturn &Adder{\n\t\tctx: ctx,\n\t\tpinning: p,\n\t\tgcLocker: bs,\n\t\tdagService: ds,\n\t\tbufferedDS: bufferedDS,\n\t\tProgress: false,\n\t\tPin: true,\n\t\tTrickle: false,\n\t\tMetaForDirectory: false,\n\t\tMetaDagToAdd: false,\n\t\tMetadataDag: nil,\n\t\tdb: nil,\n\t\tChunker: \"\",\n\t\tTokenMetadata: \"\",\n\t\tPinDuration: 0,\n\t}, nil\n}", "func NewDeduper(n int, factory func() boom.Filter) *Deduper {\n\td := &Deduper{\n\t\tring: ring.New(n),\n\t\tfactory: factory,\n\t}\n\n\t// init each element to an empty bloom filter\n\tfor i := 0; i < n; i++ {\n\t\t// expect 100k items, allow fp rate of 1%\n\t\td.ring.Value = d.factory()\n\t\td.ring = d.ring.Next()\n\t}\n\n\treturn d\n}", "func newDiseasetypeMutation(c config, op Op, opts ...diseasetypeOption) *DiseasetypeMutation {\n\tm := &DiseasetypeMutation{\n\t\tconfig: c,\n\t\top: op,\n\t\ttyp: TypeDiseasetype,\n\t\tclearedFields: make(map[string]struct{}),\n\t}\n\tfor _, opt := range opts {\n\t\topt(m)\n\t}\n\treturn m\n}", "func (d *devicelib) NewMigDevice(handle nvml.Device) (MigDevice, error) {\n\tisMig, ret := handle.IsMigDeviceHandle()\n\tif ret != nvml.SUCCESS {\n\t\treturn nil, fmt.Errorf(\"error checking if device is a MIG device: %v\", ret)\n\t}\n\tif !isMig {\n\t\treturn nil, fmt.Errorf(\"not a MIG device\")\n\t}\n\treturn &migdevice{handle, d, nil}, nil\n}", "func (a *DatumAlloc) NewDInt(v tree.DInt) *tree.DInt {\n\tif a.AllocSize == 0 {\n\t\ta.AllocSize = defaultDatumAllocSize\n\t}\n\tbuf := &a.dintAlloc\n\tif len(*buf) == 0 {\n\t\t*buf = make([]tree.DInt, a.AllocSize)\n\t}\n\tr := &(*buf)[0]\n\t*r = v\n\t*buf = (*buf)[1:]\n\treturn r\n}" ]
[ "0.6531112", "0.6350572", "0.62973064", "0.58797884", "0.5780172", "0.5770052", "0.5733969", "0.5599219", "0.55495274", "0.5385128", "0.52965933", "0.5290076", "0.5282357", "0.5248779", "0.5212722", "0.5211248", "0.51848173", "0.51848173", "0.5163079", "0.51546043", "0.50907695", "0.5080854", "0.5063953", "0.50460225", "0.50451255", "0.5043775", "0.5009722", "0.4995005", "0.4975695", "0.4974775", "0.4970688", "0.49655285", "0.49599037", "0.49325702", "0.49114838", "0.49085268", "0.4906497", "0.48336807", "0.4815352", "0.4808435", "0.47895822", "0.47848392", "0.47839358", "0.47441664", "0.47360998", "0.47127584", "0.47084585", "0.47074932", "0.46979958", "0.46828485", "0.46768826", "0.46708784", "0.46640152", "0.46584448", "0.46434772", "0.4636287", "0.46325234", "0.4616651", "0.46080187", "0.4602339", "0.4596302", "0.45955017", "0.4592103", "0.45920178", "0.4588758", "0.4588071", "0.4574635", "0.45730808", "0.45513874", "0.45460314", "0.45419657", "0.45380074", "0.4535831", "0.4526938", "0.4522224", "0.45196655", "0.45142716", "0.45098916", "0.44993848", "0.448612", "0.44856018", "0.4469613", "0.4469098", "0.44659936", "0.44609532", "0.44538823", "0.4451244", "0.44483194", "0.4445657", "0.4435726", "0.44325083", "0.44294563", "0.44187427", "0.44154754", "0.4415434", "0.44027054", "0.44024494", "0.43980616", "0.439604", "0.43959874" ]
0.76206434
0
basenameKeyFilter applies a filter on results from some iterator (e.g. the KeysPrefix store function). This is useful to filter out items located deeper in the metadata tree, but for which the simple separator rule cannot be applied.
basenameKeyFilter применяет фильтр к результатам некоторого итератора (например, функции KeysPrefix хранилища). Это полезно для отбора элементов, находящихся глубже в иерархии метаданных, но для которых не может быть применено простое правило разделителя.
func basenameKeyFilter(filter string) func([]string, string, error) ([]string, string, error) { return func(keys []string, next string, err error) ([]string, string, error) { if err != nil { return keys, next, err } filtered := make([]string, 0, len(keys)) for _, key := range keys { if !strings.HasPrefix(path.Base(key), filter) { continue } filtered = append(filtered, key) } return filtered, next, err } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func KeyHasSuffix(v string) predicate.Blob {\n\treturn predicate.Blob(\n\t\tfunc(s *sql.Selector) {\n\t\t\ts.Where(sql.HasSuffix(s.C(FieldKey), v))\n\t\t},\n\t)\n}", "func KeyHasPrefix(v string) predicate.Blob {\n\treturn predicate.Blob(\n\t\tfunc(s *sql.Selector) {\n\t\t\ts.Where(sql.HasPrefix(s.C(FieldKey), v))\n\t\t},\n\t)\n}", "func SubHasPrefix(v string) predicate.Account {\n\treturn predicate.Account(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldSub), v))\n\t})\n}", "func IterateKey(prefix string) []string {\n\tvar results []string\n\n\tdb.View(func(tx *bolt.Tx) error {\n\t\tc := tx.Bucket([]byte(DefaultBucket)).Cursor()\n\n\t\tpre := []byte(prefix)\n\t\tfor k, _ := c.Seek(pre); k != nil && bytes.HasPrefix(k, pre); k, _ = c.Next() {\n\t\t\tresults = append(results, string(k))\n\t\t}\n\t\treturn nil\n\t})\n\treturn results\n}", "func (o BucketNotificationLambdaFunctionOutput) FilterSuffix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketNotificationLambdaFunction) *string { return v.FilterSuffix }).(pulumi.StringPtrOutput)\n}", "func (v *Verb) Filter(prefix string) (result []*Verb) {\n\tfor _, child := range v.verbs {\n\t\tif strings.HasPrefix(child.Name, prefix) {\n\t\t\tresult = append(result, child)\n\t\t}\n\t}\n\treturn result\n}", "func BunameHasPrefix(v string) predicate.Building {\n\treturn predicate.Building(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldBuname), v))\n\t})\n}", "func PrefixFilter(prefix string) FilterFunc {\n\treturn func(m *MountInfo) (bool, bool) {\n\t\tskip := !strings.HasPrefix(m.MountPoint, prefix)\n\t\treturn skip, false\n\t}\n}", "func LastnameHasPrefix(v string) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldLastname), v))\n\t})\n}", "func LastNameHasPrefix(v string) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldLastName), v))\n\t})\n}", "func (o BucketNotificationTopicOutput) FilterSuffix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketNotificationTopic) *string { return v.FilterSuffix }).(pulumi.StringPtrOutput)\n}", "func (o FolderBucketViewOutput) Filter() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *FolderBucketView) pulumi.StringOutput { return v.Filter }).(pulumi.StringOutput)\n}", "func ExtractKeySuffix(key string) (string, error) {\n\tsubs := strings.Split(key, \"/\")\n\tif len(subs) < 2 {\n\t\treturn \"\", errors.Errorf(\"invalid key: %s\", key)\n\t}\n\treturn subs[len(subs)-1], nil\n}", "func BioHasPrefix(v string) predicate.User {\n\treturn predicate.User(sql.FieldHasPrefix(FieldBio, v))\n}", "func (e FlatMap) Filter(r ...*regexp.Regexp) (res FlatMap) {\n\tres = FlatMap{}\nLOOP:\n\tfor k, v := range e {\n\t\tfor _, r1 := range r {\n\t\t\tif r1.MatchString(k) {\n\t\t\t\tcontinue LOOP\n\t\t\t}\n\t\t\tres[k] = v\n\t\t}\n\t}\n\treturn\n}", "func FilterPrefix(stringSet sets.String, prefix string, ignoreCase bool) sets.String {\n\tif prefix == \"\" {\n\t\treturn stringSet\n\t}\n\treturn filterSet(stringSet, prefix, ignoreCase, strings.HasPrefix)\n}", "func BaseHasSuffix(v string) predicate.MetaSchema {\n\treturn predicate.MetaSchema(func(s *sql.Selector) {\n\t\ts.Where(sql.HasSuffix(s.C(FieldBase), v))\n\t},\n\t)\n}", "func KinNameHasSuffix(v string) predicate.Rent {\n\treturn predicate.Rent(func(s *sql.Selector) {\n\t\ts.Where(sql.HasSuffix(s.C(FieldKinName), v))\n\t})\n}", "func SplitMetaResourceNamespaceKeyFunc(key string) (kind, namespace, name string, err error) {\n\tparts := strings.Split(key, \"/\")\n\tswitch len(parts) {\n\tcase 2:\n\t\t// kind and name only\n\t\treturn parts[0], \"\", parts[1], nil\n\tcase 3:\n\t\t// kind, namespace and name\n\t\treturn parts[0], parts[1], parts[2], nil\n\t}\n\n\treturn \"\", \"\", \"\", fmt.Errorf(\"unexpected key format: %q\", key)\n}", "func filterObjectPasses(b string, k string, filter *[]string) bool {\n\n\tif !theConfig[\"oneBucket\"].BoolVal {\n\t\treturn false // never delete when we are scanning all the buckets\n\t}\n\n\t// wildcard\n\tif theConfig[\"listFilesMatchingPrefix\"].StrVal == \"*\" &&\n\t\tlen(theConfig[\"ListFilesMatchingExclude\"].StrVal) > 0 &&\n\t\t!strings.Contains(k, theConfig[\"ListFilesMatchingExclude\"].StrVal) {\n\t\treturn true // only that special case of matching\n\t}\n\n\t// now tickier cases\n\t// 1. In matching files but not in exclude list\n\tif strings.HasPrefix(k, theConfig[\"listFilesMatchingPrefix\"].StrVal) &&\n\t\tlen(theConfig[\"ListFilesMatchingExclude\"].StrVal) > 0 &&\n\t\t!strings.Contains(k, theConfig[\"listFilesMatchingExclude\"].StrVal) { // but never if the exclude thing matches\n\n\t\treturn true\n\t}\n\tif filter != nil {\n\t\tfor _, s := range *filter {\n\t\t\tif strings.HasPrefix(k, s) {\n\t\t\t\treturn true // so delete all the things in the delete file\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}", "func BunameHasSuffix(v string) predicate.Building {\n\treturn predicate.Building(func(s *sql.Selector) {\n\t\ts.Where(sql.HasSuffix(s.C(FieldBuname), v))\n\t})\n}", "func NameHasPrefix(v string) predicate.Watchlist {\n\treturn predicate.Watchlist(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldName), v))\n\t})\n}", "func KinNameHasPrefix(v string) predicate.Rent {\n\treturn predicate.Rent(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldKinName), v))\n\t})\n}", "func NameHasPrefix(v string) predicate.Product {\n\treturn predicate.Product(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldName), v))\n\t})\n}", "func (o BucketNotificationQueueOutput) FilterSuffix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketNotificationQueue) *string { return v.FilterSuffix }).(pulumi.StringPtrOutput)\n}", "func (_Bucket *BucketFilterer) FilterFileRename(opts *bind.FilterOpts, entity []common.Address) (*BucketFileRenameIterator, error) {\n\n\tvar entityRule []interface{}\n\tfor _, entityItem := range entity {\n\t\tentityRule = append(entityRule, entityItem)\n\t}\n\n\tlogs, sub, err := _Bucket.contract.FilterLogs(opts, \"FileRename\", entityRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &BucketFileRenameIterator{contract: _Bucket.contract, event: \"FileRename\", logs: logs, sub: sub}, nil\n}", "func BucketGetKeysWithPrefix(tx *bolt.Tx, bucket string, prefix string, stripPrefix bool) []string {\n\tb := tx.Bucket([]byte(bucket))\n\tif b == nil {\n\t\treturn nil\n\t}\n\tc := b.Cursor()\n\tvar results []string\n\tprefixBytes := []byte(prefix)\n\tfor k, _ := c.Seek(prefixBytes); k != nil && bytes.HasPrefix(k, prefixBytes); k, _ = c.Next() {\n\t\tif stripPrefix {\n\t\t\tk = k[len(prefix):]\n\t\t}\n\t\tresults = append(results, string(k))\n\t}\n\treturn results\n}", "func (o *Options) ObjectKeyFilterFn() ObjectKeyFilterFn { return o.objectKeyFilterFn }", "func NameHasPrefix(v string) predicate.Conversion {\n\treturn predicate.Conversion(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldName), v))\n\t})\n}", "func NameHasPrefix(v string) predicate.Book {\n\treturn predicate.Book(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldName), v))\n\t})\n}", "func filterListedVdiskID(key string) (string, bool) {\n\tparts := listStorageKeyPrefixRex.FindStringSubmatch(key)\n\tif len(parts) == 3 {\n\t\treturn parts[2], true\n\t}\n\n\treturn \"\", false\n}", "func (o BucketReplicationConfigRuleFilterTagOutput) Key() pulumi.StringOutput {\n\treturn o.ApplyT(func(v BucketReplicationConfigRuleFilterTag) string { return v.Key }).(pulumi.StringOutput)\n}", "func filterFilenames(bctx build.Context, inputs []string) ([]string, error) {\n\toutputs := []string{}\n\n\tfor _, filename := range inputs {\n\t\tfullPath, err := filepath.Abs(filename)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdir, base := filepath.Split(fullPath)\n\n\t\tmatches, err := bctx.MatchFile(dir, base)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif matches {\n\t\t\toutputs = append(outputs, filename)\n\t\t}\n\t}\n\treturn outputs, nil\n}", "func NameHasPrefix(v string) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldName), v))\n\t})\n}", "func NameHasPrefix(v string) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldName), v))\n\t})\n}", "func NameHasPrefix(v string) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldName), v))\n\t})\n}", "func (b *Bucket) GetFileEncryptionKeysForPrefix(pre string) (map[string][]byte, error) {\n\tif b.Version == 0 {\n\t\treturn map[string][]byte{\"\": b.GetLinkEncryptionKey()}, nil\n\t}\n\n\tkeys := make(map[string][]byte)\n\tfor p := range b.Metadata {\n\t\tif strings.HasPrefix(p, pre) {\n\t\t\tmd, _, ok := b.GetMetadataForPath(p, true)\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"could not resolve path: %s\", p)\n\t\t\t}\n\t\t\tkeys[p] = keyBytes(md.Key)\n\t\t}\n\t}\n\treturn keys, nil\n}", "func NameHasPrefix(v string) predicate.Watchlisthistory {\n\treturn predicate.Watchlisthistory(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldName), v))\n\t})\n}", "func SecretHasPrefix(v string) predicate.Account {\n\treturn predicate.Account(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldSecret), v))\n\t})\n}", "func AuthorHasPrefix(v string) predicate.Book {\n\treturn predicate.Book(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldAuthor), v))\n\t})\n}", "func NameHasPrefix(v string) predicate.Project {\n\treturn predicate.Project(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldName), v))\n\t})\n}", "func NameHasPrefix(v string) predicate.Project {\n\treturn predicate.Project(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldName), v))\n\t})\n}", "func fileRkfilter(line []string) []string {\n\tvar cleanfile []string\n\tfor _, l := range line {\n\t\tif len(l) > 0 && l[0] != '#' {\n\t\t\tcleanfile = append(cleanfile, l)\n\t\t}\n\t}\n\treturn cleanfile\n}", "func NameHasPrefix(v string) predicate.AllocationStrategy {\n\treturn predicate.AllocationStrategy(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldName), v))\n\t})\n}", "func (dbm *DBManager) GetKeyList(bucket, prefix string) ([]string, error) {\n\tvar err error\n\tvar results []string\n\tif err = dbm.openDB(); err != nil {\n\t\treturn nil, err\n\t}\n\tdefer dbm.closeDB()\n\n\tresults = make([]string, 0)\n\n\tseekPrefix := func(tx *boltsecTx) error {\n\t\tprefixKey := []byte(prefix)\n\n\t\tbkt := tx.Bucket([]byte(bucket))\n\n\t\tif bkt == nil {\n\t\t\treturn bolt.ErrBucketNotFound\n\t\t}\n\n\t\tcursor := bkt.Cursor()\n\t\tfor k, _ := cursor.Seek(prefixKey); k != nil && bytes.HasPrefix(k, prefixKey); k, _ = cursor.Next() {\n\t\t\tresults = append(results, string(k))\n\t\t}\n\t\treturn nil\n\t}\n\n\tif err = dbm.db.view(seekPrefix); err != nil {\n\t\tLogger.Printf(\"GetByPrefix return %s\", err)\n\t}\n\n\treturn results, err\n}", "func NameHasPrefix(v string) predicate.Ref {\n\treturn predicate.Ref(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldName), v))\n\t})\n}", "func Key(parts ...string) (k string) {\n\tfor _, v := range parts {\n\t\tif v = strings.TrimSpace(v); v == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tif k != \"\" {\n\t\t\tk += \"_\"\n\t\t}\n\t\tk += v\n\t}\n\treturn strings.ToUpper(k)\n}", "func SubHasSuffix(v string) predicate.Account {\n\treturn predicate.Account(func(s *sql.Selector) {\n\t\ts.Where(sql.HasSuffix(s.C(FieldSub), v))\n\t})\n}", "func BaseHasPrefix(v string) predicate.MetaSchema {\n\treturn predicate.MetaSchema(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldBase), v))\n\t},\n\t)\n}", "func (d *BackupDescriptor) Filter(pred func(s string) bool) {\n\tcs := make([]ClassDescriptor, 0, len(d.Classes))\n\tfor _, dest := range d.Classes {\n\t\tif pred(dest.Name) {\n\t\t\tcs = append(cs, dest)\n\t\t}\n\t}\n\td.Classes = cs\n}", "func BenefitsHasPrefix(v string) predicate.Job {\n\treturn predicate.Job(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldBenefits), v))\n\t})\n}", "func UserUploadHasSuffix(v string) predicate.Watchlist {\n\treturn predicate.Watchlist(func(s *sql.Selector) {\n\t\ts.Where(sql.HasSuffix(s.C(FieldUserUpload), v))\n\t})\n}", "func (c StringArrayCollection) Filter(cb CB) Collection {\n\tvar d = make([]string, 0)\n\tfor key, value := range c.value {\n\t\tif cb(key, value) {\n\t\t\td = append(d, value)\n\t\t}\n\t}\n\treturn StringArrayCollection{\n\t\tvalue: d,\n\t}\n}", "func SubtypeHasPrefix(v string) predicate.Block {\n\treturn predicate.Block(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldSubtype), v))\n\t})\n}", "func BuyerHasPrefix(v string) predicate.Order {\n\treturn predicate.Order(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldBuyer), v))\n\t})\n}", "func (r RawValues) FilterPrefix(prefix string) RawValues {\n\tfiltered := make(RawValues, 0)\n\tfor _, r := range r {\n\t\tif match.HasPrefix(r.Value, prefix) {\n\t\t\tfiltered = append(filtered, r)\n\t\t}\n\t}\n\treturn filtered\n}", "func basename(s string) string {\n\n\t// discard the last '/' and everything before it\n\tfor i := len(s) - 1; i >= 0; i-- {\n\t\tif s[i] == '/' {\n\t\t\ts = s[i+1:]\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// preserve everything before the last '.'\n\tfor i := len(s) - 1; i >= 0; i-- {\n\t\tif s[i] == '.' {\n\t\t\ts = s[:i]\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn s\n}", "func (blt Bolt) KeyIterator(query func([]byte) error) error {\n\tboltQuery := func(k, v []byte) error {\n\t\treturn query(k)\n\t}\n\treturn blt.db.View(func(tx *b.Tx) error {\n\t\treturn tx.Bucket(blt.Bucket).ForEach(boltQuery)\n\t})\n}", "func FilterEntriesByPrefix(prefix string, entries []string) []string {\n\tvar result []string\n\tfor _, entry := range entries {\n\t\tif strings.HasPrefix(entry, prefix) {\n\t\t\tresult = append(result, entry)\n\t\t}\n\t}\n\treturn result\n}", "func (b *Bucket) Iter(_ context.Context, dir string, f func(string) error) error {\n\tunique := map[string]struct{}{}\n\n\tfor filename := range b.objects {\n\t\tif !strings.HasPrefix(filename, dir) {\n\t\t\tcontinue\n\t\t}\n\t\tparts := strings.SplitAfter(filename, \"/\")\n\t\tunique[parts[0]] = struct{}{}\n\t}\n\tvar keys []string\n\tfor n := range unique {\n\t\tkeys = append(keys, n)\n\t}\n\tsort.Strings(keys)\n\n\tfor _, k := range keys {\n\t\tif err := f(k); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func PrefixMatch(key string) (res []interface{}) {\n\tglobalStore.RLock()\n\tdefer globalStore.RUnlock()\n\n\tfor k, v := range globalStore.store {\n\t\tif strings.HasPrefix(k, key) {\n\t\t\tres = append(res, v)\n\t\t}\n\t}\n\n\treturn\n}", "func filterUpper(ctx stick.Context, val stick.Value, args ...stick.Value) stick.Value {\n\treturn strings.ToUpper(stick.CoerceString(val))\n}", "func attributeSuffixSelector(key, val string) Selector {\n\treturn attributeSelector(key,\n\t\tfunc(s string) bool {\n\t\t\tif strings.TrimSpace(s) == \"\" {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\treturn strings.HasSuffix(s, val)\n\t\t})\n}", "func NameHasPrefix(v string) predicate.Location {\n\treturn predicate.Location(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldName), v))\n\t},\n\t)\n}", "func NameHasPrefix(v string) predicate.ValidMessage {\n\treturn predicate.ValidMessage(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldName), v))\n\t})\n}", "func (o BucketLifecycleConfigurationV2RuleFilterTagOutput) Key() pulumi.StringOutput {\n\treturn o.ApplyT(func(v BucketLifecycleConfigurationV2RuleFilterTag) string { return v.Key }).(pulumi.StringOutput)\n}", "func (g AnnotationGetter) Filter(rn *RNode) (*RNode, error) {\n\tv, err := rn.Pipe(PathGetter{Path: []string{\"metadata\", \"annotations\", g.Key}})\n\tif v == nil || err != nil {\n\t\treturn v, err\n\t}\n\tif g.Value == \"\" || v.value.Value == g.Value {\n\t\treturn v, err\n\t}\n\treturn nil, err\n}", "func DenomMetadataKey(denom string) []byte {\n\td := []byte(denom)\n\treturn append(DenomMetadataPrefix, d...)\n}", "func (f *Filter) getKey(key string) string {\n\tif f.HashKeys {\n\t\th := sha1.New()\n\t\ts := h.Sum([]byte(key))\n\t\treturn fmt.Sprintf(\"%x\", s)\n\t}\n\treturn key\n}", "func NameHasPrefix(v string) predicate.Patient {\n\treturn predicate.Patient(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldName), v))\n\t})\n}", "func FirstnameHasPrefix(v string) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldFirstname), v))\n\t})\n}", "func PhotoHasPrefix(v string) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldPhoto), v))\n\t})\n}", "func youtrackBranchNameFilter(branchName string) string {\n\tmatches := youtrackBranchNameRegEx.FindStringSubmatch(branchName)\n\tif matches != nil {\n\t\treturn fmt.Sprintf(\"%s-%s\", strings.ToUpper(matches[1]), matches[2])\n\t}\n\treturn \"\"\n}", "func (b *Bucket) RotateFileEncryptionKeysForPrefix(pre string) error {\n\tif b.Version == 0 {\n\t\treturn nil\n\t}\n\n\tfor p, md := range b.Metadata {\n\t\tif strings.HasPrefix(p, pre) {\n\t\t\tif md.Key != \"\" {\n\t\t\t\tkey, err := dcrypto.NewKey()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tmd.SetFileEncryptionKey(key)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func filterCallback(branch Branch, search []string) bool {\n\tfor i := 0; i < len(search); i++ {\n\t\tif s.Contains(branch.Name, search[i]) {\t\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func NameHasPrefix(v string) predicate.GameServer {\n\treturn predicate.GameServer(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldName), v))\n\t})\n}", "func NameHasSuffix(v string) predicate.Watchlist {\n\treturn predicate.Watchlist(func(s *sql.Selector) {\n\t\ts.Where(sql.HasSuffix(s.C(FieldName), v))\n\t})\n}", "func ExampleBucket_MapPrefix() {\n\tbx, _ := buckets.Open(tempfile())\n\tdefer os.Remove(bx.Path())\n\tdefer bx.Close()\n\n\t// Create a new things bucket.\n\tthings, _ := bx.New([]byte(\"things\"))\n\n\t// Setup items to insert.\n\titems := []struct {\n\t\tKey, Value []byte\n\t}{\n\t\t{[]byte(\"A\"), []byte(\"1\")}, // `A` prefix match\n\t\t{[]byte(\"AA\"), []byte(\"2\")}, // match\n\t\t{[]byte(\"AAA\"), []byte(\"3\")}, // match\n\t\t{[]byte(\"AAB\"), []byte(\"2\")}, // match\n\t\t{[]byte(\"B\"), []byte(\"O\")},\n\t\t{[]byte(\"BA\"), []byte(\"0\")},\n\t\t{[]byte(\"BAA\"), []byte(\"0\")},\n\t}\n\n\t// Insert 'em.\n\tif err := things.Insert(items); err != nil {\n\t\tfmt.Printf(\"could not insert items in `things` bucket: %v\\n\", err)\n\t}\n\n\t// Now collect each item whose key starts with \"A\".\n\tprefix := []byte(\"A\")\n\n\t// Setup slice of items.\n\ttype item struct {\n\t\tKey, Value []byte\n\t}\n\tresults := []item{}\n\n\t// Anon func to map over matched keys.\n\tdo := func(k, v []byte) error {\n\t\tresults = append(results, item{k, v})\n\t\treturn nil\n\t}\n\n\tif err := things.MapPrefix(do, prefix); err != nil {\n\t\tfmt.Printf(\"could not map items with prefix %s: %v\\n\", prefix, err)\n\t}\n\n\tfor _, item := range results {\n\t\tfmt.Printf(\"%s -> %s\\n\", item.Key, item.Value)\n\t}\n\t// Output:\n\t// A -> 1\n\t// AA -> 2\n\t// AAA -> 3\n\t// AAB -> 2\n}", "func filterByPrefix[T types.ResourceWithLabels](resources []T, prefix string, altNameFns ...altNameFn[T]) []T {\n\treturn filterResources(resources, func(r T) bool {\n\t\tif strings.HasPrefix(r.GetName(), prefix) {\n\t\t\treturn true\n\t\t}\n\t\tfor _, altName := range altNameFns {\n\t\t\tif strings.HasPrefix(altName(r), prefix) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t})\n}", "func PictureHasPrefix(v string) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldPicture), v))\n\t})\n}", "func PhotoHasSuffix(v string) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\ts.Where(sql.HasSuffix(s.C(FieldPhoto), v))\n\t})\n}", "func CreateWorkbookFilterFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWorkbookFilter(), nil\n}", "func TestTrimKafkaChannelServiceNameSuffix(t *testing.T) {\n\n\t// Test Data\n\tchannelName := \"TestChannelName\"\n\tchannelServiceName := fmt.Sprintf(\"%s-%s\", channelName, constants.KafkaChannelServiceNameSuffix)\n\n\t// Perform The Test\n\tactualResult := TrimKafkaChannelServiceNameSuffix(channelServiceName)\n\n\t// Verify The Results\n\texpectedResult := channelName\n\tassert.Equal(t, expectedResult, actualResult)\n}", "func (s *s3) List(key string) ([]string, error) {\n\tif key != \"\" && !strings.HasSuffix(key, \"/\") {\n\t\tkey += \"/\"\n\t}\n\n\tresult, err := s.client.ListObjectsV2(&awss3.ListObjectsV2Input{\n\t\tPrefix: aws.String(key),\n\t\tBucket: aws.String(s.bucket),\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfiles := []string{}\n\tfor _, obj := range result.Contents {\n\t\t_, file := path.Split(*obj.Key)\n\t\tfiles = append(files, file)\n\t}\n\treturn files, nil\n}", "func FundTitleHasPrefix(v string) predicate.CoveredPerson {\n\treturn predicate.CoveredPerson(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldFundTitle), v))\n\t})\n}", "func TaxIDHasPrefix(v string) predicate.Watchlist {\n\treturn predicate.Watchlist(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldTaxID), v))\n\t})\n}", "func extractKey(key string, content *string) string {\n\tif loc := strings.Index(*content, key); loc != -1 {\n\t\tv := (*content)[loc+len(key):]\n\t\tsep := v[:1]\n\t\tv = v[1:][:strings.Index(v[1:], sep)]\n\t\treturn v\n\t}\n\treturn \"\"\n}", "func (r *Registry) filter(glob string, fn func(element interface{})) RangeFunc {\n\treturn func(key, value interface{}) bool {\n\t\tif ok, err := filepath.Match(glob, key.(string)); ok {\n\t\t\tfn(value)\n\t\t} else if err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn true\n\t}\n}", "func SocialNameHasPrefix(v string) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldSocialName), v))\n\t})\n}", "func TestMapPrefix(t *testing.T) {\n\tbx := NewTestDB()\n\tdefer bx.Close()\n\n\t// Create a new things bucket.\n\tthings, err := bx.New([]byte(\"things\"))\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t}\n\n\t// Setup items to insert.\n\titems := []struct {\n\t\tKey, Value []byte\n\t}{\n\t\t{[]byte(\"A\"), []byte(\"1\")}, // `A` prefix match\n\t\t{[]byte(\"AA\"), []byte(\"2\")}, // match\n\t\t{[]byte(\"AAA\"), []byte(\"3\")}, // match\n\t\t{[]byte(\"AAB\"), []byte(\"2\")}, // match\n\t\t{[]byte(\"B\"), []byte(\"O\")},\n\t\t{[]byte(\"BA\"), []byte(\"0\")},\n\t\t{[]byte(\"BAA\"), []byte(\"0\")},\n\t}\n\n\t// Insert 'em.\n\tif err := things.Insert(items); err != nil {\n\t\tt.Error(err.Error())\n\t}\n\n\t// Now collect each item whose key starts with \"A\".\n\tprefix := []byte(\"A\")\n\n\t// Expected items for keys with prefix \"A\".\n\texpected := []struct {\n\t\tKey, Value []byte\n\t}{\n\t\t{[]byte(\"A\"), []byte(\"1\")},\n\t\t{[]byte(\"AA\"), []byte(\"2\")},\n\t\t{[]byte(\"AAA\"), []byte(\"3\")},\n\t\t{[]byte(\"AAB\"), []byte(\"2\")},\n\t}\n\n\t// Setup slice of items to collect results.\n\ttype item struct {\n\t\tKey, Value []byte\n\t}\n\tresults := []item{}\n\n\t// Anon func to map over matched keys.\n\tdo := func(k, v []byte) error {\n\t\tresults = append(results, item{k, v})\n\t\treturn nil\n\t}\n\n\tif err := things.MapPrefix(do, prefix); err != nil {\n\t\tt.Error(err.Error())\n\t}\n\n\tfor i, want := range expected {\n\t\tgot := results[i]\n\t\tif !bytes.Equal(got.Key, want.Key) {\n\t\t\tt.Errorf(\"got %v, want %v\", got.Key, want.Key)\n\t\t}\n\t\tif !bytes.Equal(got.Value, want.Value) {\n\t\t\tt.Errorf(\"got %v, want %v\", got.Value, want.Value)\n\t\t}\n\t}\n}", "func DetialHasPrefix(v string) predicate.Medicalfile {\n\treturn predicate.Medicalfile(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldDetial), v))\n\t})\n}", "func (s *ServiceRecordedTestsSuite) TestAccountFilterBlobs() {\n\t_require := require.New(s.T())\n\tsvcClient, err := testcommon.GetServiceClient(s.T(), testcommon.TestAccountDefault, nil)\n\t_require.NoError(err)\n\n\tfilter := \"\\\"key\\\"='value'\"\n\tresp, err := svcClient.FilterBlobs(context.Background(), filter, &service.FilterBlobsOptions{})\n\t_require.Nil(err)\n\t_require.Len(resp.FilterBlobSegment.Blobs, 0)\n}", "func FirstNameHasPrefix(v string) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldFirstName), v))\n\t})\n}", "func BuildRemoveLabelFilter(predicate func(key string) bool) (yaml.Filter, error) {\n\tfieldPaths, err := xform.ParseFieldPaths(\n\t\t[]string{\n\t\t\t\"metadata.labels\",\n\t\t\t\"spec.selector\",\n\t\t\t\"spec.selector.matchLabels\",\n\t\t\t\"spec.template.metadata.labels\",\n\t\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &xform.FieldClearer{\n\t\tFieldPaths: fieldPaths,\n\t\tPredicate: predicate,\n\t}, nil\n}", "func SplitKey(key string) (string, string) {\n\tif !strings.Contains(key, \"/\") {\n\t\treturn key, \"\"\n\t}\n\tkeyParts := strings.SplitN(key, \"/\", 2)\n\treturn keyParts[0], keyParts[1]\n}", "func normalizeResourceName(inKey string) string {\n\n\toutKey := \"\"\n\tre := regexp.MustCompile(\"^[a-zA-Z0-9_-]*$\")\n\tfor i, char := range inKey {\n\t\tschar := string(char)\n\t\tif i == 0 {\n\t\t\tfc := regexp.MustCompile(\"^[a-zA-Z_]*$\")\n\t\t\tif !fc.MatchString(schar) {\n\t\t\t\toutKey += \"_\"\n\t\t\t}\n\t\t}\n\t\tif re.MatchString(schar) {\n\t\t\toutKey += schar\n\t\t} else {\n\t\t\toutKey += \"_\"\n\t\t}\n\t}\n\treturn outKey\n\n}", "func (g *gbkBinCollator) KeyWithoutTrimRightSpace(str string) []byte {\n\tbuf := make([]byte, 0, len(str))\n\tfor len(str) > 0 {\n\t\tl := runeLen(str[0])\n\t\tgbk, err := g.e.Bytes(hack.Slice(str[:l]))\n\t\tif err != nil {\n\t\t\tbuf = append(buf, byte('?'))\n\t\t} else {\n\t\t\tbuf = append(buf, gbk...)\n\t\t}\n\t\tstr = str[l:]\n\t}\n\n\treturn buf\n}", "func UserUploadHasPrefix(v string) predicate.Watchlist {\n\treturn predicate.Watchlist(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldUserUpload), v))\n\t})\n}", "func SecretHasSuffix(v string) predicate.Account {\n\treturn predicate.Account(func(s *sql.Selector) {\n\t\ts.Where(sql.HasSuffix(s.C(FieldSecret), v))\n\t})\n}", "func (o BucketNotificationLambdaFunctionOutput) FilterPrefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketNotificationLambdaFunction) *string { return v.FilterPrefix }).(pulumi.StringPtrOutput)\n}" ]
[ "0.52340424", "0.4928137", "0.4894693", "0.4847061", "0.47071567", "0.46861228", "0.4669897", "0.46603027", "0.46325058", "0.4622332", "0.46086925", "0.4532329", "0.45094556", "0.44940478", "0.4484004", "0.44813517", "0.4467792", "0.44648084", "0.44573885", "0.4454603", "0.4444005", "0.44415364", "0.43906486", "0.43894365", "0.43863362", "0.43743628", "0.43710116", "0.43668833", "0.43644872", "0.43558052", "0.43514878", "0.43453282", "0.43114075", "0.43071324", "0.43071324", "0.43071324", "0.42884612", "0.42785546", "0.4269324", "0.42678303", "0.4260513", "0.4260513", "0.42490265", "0.4246136", "0.42402586", "0.42390937", "0.42375287", "0.42355996", "0.4233639", "0.42134", "0.4202226", "0.41974056", "0.41924983", "0.4191894", "0.41914374", "0.4191122", "0.41744962", "0.41728833", "0.41724458", "0.41654408", "0.41464183", "0.4141171", "0.41402188", "0.4135609", "0.41352314", "0.41157433", "0.41103798", "0.41084903", "0.41064742", "0.40963835", "0.40906423", "0.40883255", "0.4082987", "0.40809464", "0.4077835", "0.40650398", "0.40585554", "0.40564835", "0.40460217", "0.40451545", "0.4040305", "0.40403005", "0.40330538", "0.4023306", "0.40193436", "0.4015472", "0.40116563", "0.40113947", "0.40110296", "0.40100732", "0.40035397", "0.40024048", "0.39983034", "0.3997722", "0.39964375", "0.39952242", "0.3992893", "0.39928058", "0.39914528", "0.39896727" ]
0.81313115
0
NewRolloutBlockLister returns a new RolloutBlockLister.
NewRolloutBlockLister возвращает новый RolloutBlockLister.
func NewRolloutBlockLister(indexer cache.Indexer) RolloutBlockLister { return &rolloutBlockLister{indexer: indexer} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s rolloutBlockNamespaceLister) Get(name string) (*v1alpha1.RolloutBlock, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"rolloutblock\"), name)\n\t}\n\treturn obj.(*v1alpha1.RolloutBlock), nil\n}", "func (s rolloutBlockNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.RolloutBlock, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.RolloutBlock))\n\t})\n\treturn ret, err\n}", "func (s *rolloutBlockLister) RolloutBlocks(namespace string) RolloutBlockNamespaceLister {\n\treturn rolloutBlockNamespaceLister{indexer: s.indexer, namespace: namespace}\n}", "func (s *rolloutBlockLister) List(selector labels.Selector) (ret []*v1alpha1.RolloutBlock, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.RolloutBlock))\n\t})\n\treturn ret, err\n}", "func New() *Blockstream {\n\treturn &Blockstream{}\n}", "func New(storage Storage) *Block {\n\tb := Block{\n\t\tstorage: storage,\n\t}\n\tb.Transactions = make([]transaction.Transaction, 0, 0)\n\treturn &b\n}", "func NewBlock(object dbus.BusObject) *Block {\n\treturn &Block{object}\n}", "func NewBlock(tx *Transaction) *Block {\n\t\n\treturn nil\n}", "func NewBundleLister(indexer cache.Indexer) BundleLister {\n\treturn &bundleLister{indexer: indexer}\n}", "func NewBlock() *Block {\n\treturn &Block{}\n}", "func New() *block {\n\treturn &block{\n\t\tbroadcastChan: make(chan Message, broadcastChanSize),\n\t\tbroadcastMsgSeen: map[string]struct{}{},\n\t}\n}", "func (t *Blockchain) New() *Blockchain {\n\tt = new(Blockchain)\n\tt.NewBlock(100, \"1\")\n\treturn t\n}", "func (c *Client) NewBlockFilter() (*QuantityResponse, error) {\n\trequest := c.newRequest(EthNewBlockFilter)\n\n\tresponse := &QuantityResponse{}\n\n\treturn response, c.send(request, response)\n}", "func NewBlock(typeName string, labels []string) *Block {\n\tblock := newBlock()\n\tblock.init(typeName, labels)\n\treturn block\n}", "func NewBlock(typeName string, labels []string) *Block {\n\tblock := newBlock()\n\tblock.init(typeName, labels)\n\treturn block\n}", "func NewBlock(index idx.Block, time Timestamp, events hash.Events, prevHash hash.Event) *Block {\n\treturn &Block{\n\t\tIndex: index,\n\t\tTime: time,\n\t\tEvents: events,\n\t\tPrevHash: prevHash,\n\t\tSkippedTxs: make([]uint, 0),\n\t}\n}", "func NewBlock(statements []sql.Node) *Block {\n\treturn &Block{statements: statements}\n}", "func NewBlockFilter(\n\tlogger log.Logger,\n\tlabelSelector labels.Selector,\n\tresolutionLevel compact.ResolutionLevel,\n\tcompactionLevel int,\n) *BlockFilter {\n\treturn &BlockFilter{\n\t\tlabelSelector: labelSelector,\n\t\tlogger: logger,\n\t\tresolutionLevel: resolutionLevel,\n\t\tcompactionLevel: compactionLevel,\n\t}\n}", "func NewBlock(b *block.Block, chain blockchainer.Blockchainer) Block {\n\tres := Block{\n\t\tBlock: *b,\n\t\tBlockMetadata: BlockMetadata{\n\t\t\tSize: io.GetVarSize(b),\n\t\t\tConfirmations: chain.BlockHeight() - b.Index + 1,\n\t\t},\n\t}\n\n\thash := chain.GetHeaderHash(int(b.Index) + 1)\n\tif !hash.Equals(util.Uint256{}) {\n\t\tres.NextBlockHash = &hash\n\t}\n\n\treturn res\n}", "func NewBlock() (*Block, error) {\n\tn, err := findLast()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\th, err := ftoh(n)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfmt.Println(\"Hash: \" + h)\n\n\treturn &Block{Number: n + 1, PreviousHash: h}, nil\n}", "func NewLister() Lister {\n\treturn _lister{\n\t\tioUtil: iioutil.New(),\n\t\tdotYmlUnmarshaller: dotyml.NewUnmarshaller(),\n\t}\n}", "func NewHookLister(indexer cache.Indexer) HookLister {\n\treturn &hookLister{indexer: indexer}\n}", "func (*llcFactory) New(args *xreg.XactArgs) xreg.BucketEntry {\n\treturn &llcFactory{t: args.T, uuid: args.UUID}\n}", "func NewBlock(data *models.Block, opts ...options.Option[Block]) (newBlock *Block) {\n\treturn options.Apply(&Block{\n\t\tstrongChildren: make([]*Block, 0),\n\t\tweakChildren: make([]*Block, 0),\n\t\tlikedInsteadChildren: make([]*Block, 0),\n\t\tModelsBlock: data,\n\t}, opts)\n}", "func NewBlockchain() *Blockchain {\n\treturn CreateBlockchain()\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 (bc *Blockchain) chainNewBlock(nonce int, previousHash [32]byte) *Block {\n\tb := NewBlock(nonce, previousHash, bc.transactionPool)\n\tbc.chain = append(bc.chain, b)\n\tbc.transactionPool = []*Transaction{}\n\treturn b\n}", "func NewBlockTranslator(cfg Config, client evmclient.Client, lggr logger.Logger) BlockTranslator {\n\tswitch cfg.ChainType() {\n\tcase config.ChainArbitrum:\n\t\treturn NewArbitrumBlockTranslator(client, lggr)\n\tcase config.ChainXDai, config.ChainMetis, config.ChainOptimismBedrock:\n\t\tfallthrough\n\tdefault:\n\t\treturn &l1BlockTranslator{}\n\t}\n}", "func NewBlockCache(capacity uint32) *BlockCache {\n\t// TODO: Fetch latest block number every 15s to know what can be cached\n\t// https://eth.wiki/json-rpc/API#eth_blocknumber\n\t// curl https://cloudflare-eth.com --data '{\"jsonrpc\":\"2.0\",\"method\":\"eth_blockNumber\",\"params\":[],\"id\":1}'\n\treturn &BlockCache{\n\t\tentries: make(blockByNumberMap, capacity),\n\t\tcallCount: 0,\n\t\tcapacity: capacity,\n\t}\n}", "func NewBlockFilter() Filter {\n\treturn &blockFilter{}\n}", "func NewBlock(index int, data interface{}, date time.Time) *Block {\n\treturn &Block{\n\t\tIndex: index,\n\t\tDate: date,\n\t\tData: data,\n\t}\n}", "func NewBlock(version uint32,\n\tprevBlock []byte,\n\tmerkleRoot []byte,\n\ttimestamp uint32,\n\tbits []byte,\n\tnonce []byte,\n\ttotal uint32,\n\thashes [][]byte,\n\tflags []byte) *Block {\n\tresult := &Block{\n\t\tVersion: version,\n\t\tTimestamp: timestamp,\n\t\tTotal: total,\n\t\tHashes: hashes,\n\t\tFlags: flags,\n\t}\n\tcopy(result.PrevBlock[:32], prevBlock)\n\tcopy(result.MerkleRoot[:32], merkleRoot)\n\tcopy(result.Bits[:4], bits)\n\tcopy(result.Nonce[:4], nonce)\n\treturn result\n}", "func NewBlockchain(chain ...Block) *Blockchain {\n\treturn &Blockchain{chain}\n}", "func (I *Blockchain) NewBlock(proof uint64, previousHash string) {\n\t// In order to be able to create the first block\n\tif previousHash == \"\" {\n\t\tpreviousHash = \"1\"\n\t}\n\t// Create the block\n\tb := block{\n\t\tindex: I.currentIndex,\n\t\ttimestamp: time.Now().UnixNano(),\n\t\tproof: proof,\n\t\tpreviousHash: previousHash,\n\t\ttransactions: I.currentTransactions,\n\t}\n\t// Append the new block\n\tI.blocks = append(I.blocks, b)\n\t// Reset the transactions\n\tI.currentTransactions = make([]transaction, 0)\n\t// Update the index\n\tI.currentIndex += 1\n\t// Modify the last block variable\n\tI.lastBlock = b\n}", "func (blockchain *Blockchain) MineNewBlock(originalTxs []*Transaction) *Block {\n\t// Reward of mining a block\n\tcoinBaseTransaction := NewRewardTransacion()\n\ttxs := []*Transaction{coinBaseTransaction}\n\ttxs = append(txs, originalTxs...)\n\t// Verify transactions\n\tfor _, tx := range txs {\n\t\tif !tx.IsCoinBaseTransaction() {\n\t\t\tif blockchain.VerifityTransaction(tx, txs) == false {\n\t\t\t\tlog.Panic(\"Verify transaction failed...\")\n\t\t\t}\n\t\t}\n\t}\n\n\tDBName := fmt.Sprintf(DBName, os.Getenv(\"NODE_ID\"))\n\tdb, err := bolt.Open(DBName, 0600, nil)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\tdefer db.Close()\n\t// Get the latest block\n\tvar block Block\n\terr = db.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(BlockBucketName))\n\t\tif b != nil {\n\t\t\thash := b.Get([]byte(\"l\"))\n\t\t\tblockBytes := b.Get(hash)\n\t\t\tgobDecode(blockBytes, &block)\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\t// Mine a new block\n\tnewBlock := NewBlock(txs, block.Height+1, block.BlockHash)\n\n\treturn newBlock\n}", "func NewBlockCache() *BlockCache {\n\treturn &BlockCache{\n\t\tm: make(map[string]bool),\n\t}\n}", "func (a *insight) NewBlock(id interface{}) *block {\n\tb := new(block)\n\tb.insight = a\n\tswitch v := id.(type) {\n\tcase int:\n\t\tb.Height = int(v)\n\t\tb.hash()\n\t\tb.pages()\n\t\tb.info()\n\t\treturn b\n\tcase string:\n\t\tb.Hash = string(v)\n\t\tb.pages()\n\t\tb.info()\n\t\treturn b\n\tcase nil:\n\t\treturn b.latestBlock()\n\t}\n\treturn nil\n}", "func newBlockfileMgr(id string, conf *Conf, indexConfig *blkstorage.IndexConfig, indexStore *leveldbhelper.DBHandle) *blockfileMgr {\n\tlogger.Debugf(\"newBlockfileMgr() initializing file-based block storage for ledger: %s \", id)\n\tvar rwMutexs []*sync.RWMutex\n\n\t//Determine the root directory for the blockfile storage, if it does not exist create it\n\trootDir := conf.getLedgerBlockDir(id)\n\t_, err := util.CreateDirIfMissing(rootDir)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Error: %s\", err))\n\t}\n\t// Instantiate the manager, i.e. blockFileMgr structure\n\tmgr := &blockfileMgr{rootDir: rootDir, conf: conf, db: indexStore, rwMutexs: rwMutexs}\n\n\t// cp = checkpointInfo, retrieve from the database the file suffix or number of where blocks were stored.\n\t// It also retrieves the current size of that file and the last block number that was written to that file.\n\t// At init checkpointInfo:latestFileChunkSuffixNum=[0], latestFileChunksize=[0], lastBlockNumber=[0]\n\tcpInfo, err := mgr.loadCurrentInfo()\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Could not get block file info for current block file from db: %s\", err))\n\t}\n\tif cpInfo == nil {\n\t\tlogger.Info(`Getting block information from block storage`)\n\t\tif cpInfo, err = constructCheckpointInfoFromBlockFiles(rootDir); err != nil {\n\t\t\tpanic(fmt.Sprintf(\"Could not build checkpoint info from block files: %s\", err))\n\t\t}\n\t\tlogger.Debugf(\"Info constructed by scanning the blocks dir = %s\", spew.Sdump(cpInfo))\n\t} else {\n\t\tlogger.Debug(`Synching block information from block storage (if needed)`)\n\t\tsyncCPInfoFromFS(rootDir, cpInfo)\n\t}\n\terr = mgr.saveCurrentInfo(cpInfo, true)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Could not save next block file info to db: %s\", err))\n\t}\n\n\tmgr.oldestFileChunkSuffixNum = syncOldestFileNum(rootDir)\n\t//If start up is a restart of an existing storage,new the rwMutex for the files\n\tif conf.dumpConf.Enabled {\n\t\tfor i := 0; i <= cpInfo.latestFileChunkSuffixNum; i++ {\n\t\t\trwMutex := new(sync.RWMutex)\n\t\t\tmgr.rwMutexs = append(mgr.rwMutexs, rwMutex)\n\t\t}\n\t}\n\tmgr.dumpMutex = new(sync.Mutex)\n\n\t//Open a writer to the file identified by the number and truncate it to only contain the latest block\n\t// that was completely saved (file system, index, cpinfo, etc)\n\tcurrentFileWriter, err := newBlockfileWriter(deriveBlockfilePath(rootDir, cpInfo.latestFileChunkSuffixNum))\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Could not open writer to current file: %s\", err))\n\t}\n\t//Truncate the file to remove excess past last block\n\terr = currentFileWriter.truncateFile(cpInfo.latestFileChunksize)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Could not truncate current file to known size in db: %s\", err))\n\t}\n\n\t// Create a new KeyValue store database handler for the blocks index in the keyvalue database\n\tmgr.index = newBlockIndex(indexConfig, indexStore)\n\n\t// Update the manager with the checkpoint info and the file writer\n\tmgr.cpInfo = cpInfo\n\tmgr.currentFileWriter = currentFileWriter\n\t// Create a checkpoint condition (event) variable, for the goroutine waiting for\n\t// or announcing the occurrence of an event.\n\tmgr.cpInfoCond = sync.NewCond(&sync.Mutex{})\n\n\t// init BlockchainInfo for external API's\n\tbcInfo := &common.BlockchainInfo{\n\t\tHeight: 0,\n\t\tCurrentBlockHash: nil,\n\t\tPreviousBlockHash: nil}\n\n\tif !cpInfo.isChainEmpty {\n\t\t//If start up is a restart of an existing storage, sync the index from block storage and update BlockchainInfo for external API's\n\t\tmgr.syncIndex()\n\t\tlastBlockHeader, err := mgr.retrieveBlockHeaderByNumber(cpInfo.lastBlockNumber)\n\t\tif err != nil {\n\t\t\tpanic(fmt.Sprintf(\"Could not retrieve header of the last block form file: %s\", err))\n\t\t}\n\t\tlastBlockHash := lastBlockHeader.Hash()\n\t\tpreviousBlockHash := lastBlockHeader.PreviousHash\n\t\tbcInfo = &common.BlockchainInfo{\n\t\t\tHeight: cpInfo.lastBlockNumber + 1,\n\t\t\tCurrentBlockHash: lastBlockHash,\n\t\t\tPreviousBlockHash: previousBlockHash}\n\t}\n\tmgr.bcInfo.Store(bcInfo)\n\treturn mgr\n}", "func NewBlock(blk *types.Block, repo repository.Repository) *Block {\n\treturn &Block{\n\t\trepo: repo,\n\t\tBlock: *blk,\n\t}\n}", "func NewSMBLister(indexer cache.Indexer) SMBLister {\n\treturn &sMBLister{indexer: indexer}\n}", "func NewBlock(oldBlock Block, data string) Block {\n\t// fmt.Println(\"******TODO: IMPLEMENT NewBlock!******\")\n\tblock := Block{Data: data, Timestamp: time.Now().Unix(), PrevHash: oldBlock.Hash, Hash: []byte{}}\n\tblock.Hash = block.calculateHash()\n\t// fmt.Println(\"data: \" + block.Data)\n\t// fmt.Printf(\"timestamp: %d\", block.Timestamp)\n\t// fmt.Println()\n\t// fmt.Printf(\"preHash: %x\", block.PrevHash)\n\t// fmt.Println()\n\t// fmt.Printf(\"currentHash: %x\", block.Hash)\n\t// fmt.Println()\n\t// fmt.Println(\"******TODO: END NewBlock!******\")\n\t// fmt.Println()\n\t// fmt.Println()\n\t// fmt.Println()\n\treturn block\n}", "func NewBlockTranslator(chain Chain, client eth.Client) BlockTranslator {\n\tif chain.IsArbitrum() {\n\t\treturn NewArbitrumBlockTranslator(client)\n\t} else if chain.IsOptimism() {\n\t\treturn newOptimismBlockTranslator()\n\t}\n\treturn &l1BlockTranslator{}\n}", "func NewBlock(t *testing.T, bc blockchainer.Blockchainer, offset uint32, primary uint32, txs ...*transaction.Transaction) *block.Block {\n\twitness := transaction.Witness{VerificationScript: MultisigVerificationScript()}\n\theight := bc.BlockHeight()\n\th := bc.GetHeaderHash(int(height))\n\thdr, err := bc.GetHeader(h)\n\trequire.NoError(t, err)\n\tb := &block.Block{\n\t\tHeader: block.Header{\n\t\t\tPrevHash: hdr.Hash(),\n\t\t\tTimestamp: (uint64(time.Now().UTC().Unix()) + uint64(hdr.Index)) * 1000,\n\t\t\tIndex: hdr.Index + offset,\n\t\t\tPrimaryIndex: byte(primary),\n\t\t\tNextConsensus: witness.ScriptHash(),\n\t\t\tScript: witness,\n\t\t},\n\t\tTransactions: txs,\n\t}\n\tb.RebuildMerkleRoot()\n\n\tb.Script.InvocationScript = Sign(b)\n\treturn b\n}", "func NewBlock(hash string) *pfs.Block {\n\treturn &pfs.Block{\n\t\tHash: hash,\n\t}\n}", "func (cm *chainManager) MintNewBlock(timestamp time.Time) (*block.Block, error) {\n\treturn cm.bc.MintNewBlock(timestamp)\n}", "func (s *service) MineNewBlock(lastBlock *Block, data []Transaction) (*Block, error) {\n\t// validations\n\tif lastBlock == nil {\n\t\treturn nil, ErrMissingLastBlock\n\t}\n\n\tdifficulty := lastBlock.Difficulty\n\tvar nonce uint32\n\tvar timestamp int64\n\tvar hash string\n\tfor {\n\t\tnonce++\n\t\ttimestamp = time.Now().UnixNano()\n\t\tdifficulty = adjustBlockDifficulty(*lastBlock, timestamp, s.MineRate)\n\t\thash = hashing.SHA256Hash(timestamp, *lastBlock.Hash, data, nonce, difficulty)\n\t\tif hexStringToBinary(hash)[:difficulty] == strings.Repeat(\"0\", int(difficulty)) {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn yieldBlock(timestamp, lastBlock.Hash, &hash, data, nonce, difficulty), nil\n}", "func (self *BlockChain) NewBlock(proof int, previous_hash string) {\n\n\t// check if previous hash matches self.hash(self.chain[-1])\n\tt := time.Now()\n\n\tblock := Block{\n\t\tIndex: len(self.Chain) + 1,\n\t\tTimestamp: t.UnixNano(),\n\t\tTransactions: self.CurrentTransactions,\n\t\tProof: proof,\n\t\tPreviousHash: previous_hash}\n\n\t// Reset the current list of transactions\n\tself.CurrentTransactions = nil\n\tself.Chain = append(self.Chain, block)\n}", "func NewBlock(transactions []*Transaction, prevBlockHash []byte, height int) *Block {\n\tblock := &Block{time.Now().Unix(), transactions, prevBlockHash, []byte{}, 0, height}\n\tblock.POW()\n\treturn block\n}", "func NewBlock(data *SPOTuple, prevBlockHash string) (*Block, error) {\n\n\tblock := &Block{\n\t\tBlockId: nuid.Next(),\n\t\tData: data,\n\t\tPrevBlockHash: prevBlockHash,\n\t\tHash: \"\",\n\t\tSig: \"\",\n\t\tAuthor: cs.PublicID(),\n\t\tSender: cs.PublicID(),\n\t}\n\n\t// assign new hash\n\tblock.setHash()\n\n\t// now sign the completed block\n\terr := block.sign()\n\tif err != nil {\n\t\tlog.Println(\"unable to sign block: \", err)\n\t\treturn nil, err\n\t}\n\n\treturn block, nil\n}", "func NewRawBlock() *RawBlock {\n\treturn &RawBlock{}\n}", "func (s Store) GetBlock (hash string) (*types.FullSignedBlock, error) {\r\n\t// Open badger\r\n\tstor, err := badger.Open(badger.DefaultOptions(s.StorFileLocation))\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\r\n\tdefer stor.Close()\r\n\r\n\tvar block types.FullSignedBlock\r\n\terr = stor.Update(func(txn *badger.Txn) error {\r\n\t\tbytes, err := readStringIndex (txn, hash, HashKeyPrefix)\r\n\t\tif err != nil{\r\n\t\t\treturn err\r\n\t\t}\r\n\t\terr = json.Unmarshal(bytes, &block)\r\n\r\n\t\treturn err\r\n\t})\r\n\r\n\treturn &block, err\r\n}", "func NewBlockHandler(state *state.State, blockRefeeder *BlockRefeeder) *BlockHandler {\r\n\tresult := BlockHandler{\r\n\t\tstate: state,\r\n\t\tblockRefeeder: blockRefeeder,\r\n\t}\r\n\treturn &result\r\n}", "func (brf *BlockReaderFactory) newBlockReader(peer DomainPeer) (BlockReader, error) {\n\n\t// A read request to a datanode:\n\t// +-----------------------------------------------------------+\n\t// | Data Transfer Protocol Version, int16 |\n\t// +-----------------------------------------------------------+\n\t// | Op code, 1 byte (READ_BLOCK = 0x51) |\n\t// +-----------------------------------------------------------+\n\t// | varint length + OpReadBlockProto |\n\t// +-----------------------------------------------------------+\n\n\tproto := &OpReadBlockProto{\n\t\tHeader: &ClientOperationHeaderProto{\n\t\t\tBaseHeader: &BaseHeaderProto{\n\t\t\t\tBlock: &brf.block,\n\t\t\t\tToken: &brf.blockToken,\n\t\t\t},\n\t\t\tClientName: proto.String(brf.clientName),\n\t\t},\n\t\tOffset: proto.Uint64(uint64(brf.startOffset)),\n\t\tLen: proto.Uint64(uint64(brf.length)),\n\t\tSendChecksums: proto.Bool(brf.verifyChecksum),\n\t}\n\tif err := WriteBlockOpRequest(peer.out, ReadBlockOp, proto); err != nil {\n\t\t//todo\n\t\treturn nil, err\n\t} else {\n\t\tif status, err := ReadBlockOpResponse(peer.in); err != nil {\n\t\t\t//todo\n\t\t\treturn nil, err\n\t\t} else {\n\t\t\tif *status.Status != Status_SUCCESS {\n\t\t\t\tif *status.Status == Status_ERROR_ACCESS_TOKEN {\n\t\t\t\t\treturn nil, fmt.Errorf(\"Got access token error,status message %s \\n\", status.GetMessage())\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, fmt.Errorf(\"Got error,status message %s \\n\", status.GetMessage())\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tchecksumInfo := status.GetReadOpChecksumInfo()\n\t\t\t\tchecksum := checksumInfo.GetChecksum()\n\n\t\t\t\tfirstChunkOffset := int64(checksumInfo.GetChunkOffset())\n\n\t\t\t\tif firstChunkOffset < 0 || firstChunkOffset > brf.startOffset || firstChunkOffset <= (brf.startOffset-int64(checksum.GetBytesPerChecksum())) {\n\t\t\t\t\t//todo\n\t\t\t\t\treturn nil, fmt.Errorf(\"BlockReader: error in first chunk offset ( %d ) startOffset is %d for file %s\\n\", firstChunkOffset, brf.startOffset, brf.fileName)\n\t\t\t\t}\n\n\t\t\t\tif dataChecksum, err := NewDataChecksum(checksum); err != nil {\n\t\t\t\t\t//todo\n\t\t\t\t\treturn nil, fmt.Errorf(\"BlockReader: error in NewDataChecksum err is %s \\n\", err)\n\t\t\t\t} else {\n\t\t\t\t\tblockReader := NewRemoteBlockReader(brf.fileName, int64(brf.block.GetBlockId()), dataChecksum, brf.verifyChecksum,\n\t\t\t\t\t\tbrf.startOffset, firstChunkOffset, brf.length, peer, *brf.datanode.GetId())\n\t\t\t\t\treturn blockReader, nil\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\t}\n\n}", "func (wc *WalletClient) NewBlock(b Block) error {\n\t_, err := wc.POST(\"/new-block\", b.Json())\n\treturn err\n}", "func newBlock(lastBlock Block, seed int, npeer string, transactions []SignedTransaction) Block {\n\tvar newBlock Block\n\n\tnewBlock.Seed = seed\n\tnewBlock.Index = lastBlock.Index + 1\n\tnewBlock.LastHash = lastBlock.Hash\n\tnewBlock.Peer = npeer\n\tnewBlock.SpecialAccounts = lastBlock.SpecialAccounts\n\tnewBlock.Transactions = transactions\n\tnewBlock.Hash = blockHash(newBlock)\n\treturn newBlock\n}", "func NewBlockReader(salt crypto.Salt, pass []byte, cipher crypto.Cipher) BlockReader {\n\tkey := salt.Apply(pass, cipher.KeySize())\n\treturn BlockReaderFn(func(b secret.Block) ([]byte, error) {\n\t\treturn b.Decrypt(key)\n\t})\n}", "func NewBlock(index uint64, ordered Events) *Block {\n\tevents := make(hash.EventsSlice, len(ordered))\n\tfor i, e := range ordered {\n\t\tevents[i] = e.Hash()\n\t}\n\n\treturn &Block{\n\t\tIndex: index,\n\t\tEvents: events,\n\t}\n}", "func NewBlock(chain uint64, producer Address) *StBlock {\n\tvar hashPowerLimit uint64\n\tvar blockInterval uint64\n\tvar pStat BaseInfo\n\tout := new(StBlock)\n\tgetDataFormDB(chain, dbStat{}, []byte{StatBaseInfo}, &pStat)\n\tgetDataFormDB(chain, dbStat{}, []byte{StatHashPower}, &hashPowerLimit)\n\tgetDataFormDB(chain, dbStat{}, []byte{StatBlockInterval}, &blockInterval)\n\n\tif pStat.ID == 0 {\n\t\tlog.Println(\"fail to get the last block. chain:\", chain)\n\t\treturn nil\n\t}\n\n\thashPowerLimit = hashPowerLimit / 1000\n\tif hashPowerLimit < minHPLimit {\n\t\thashPowerLimit = minHPLimit\n\t}\n\n\tout.HashpowerLimit = hashPowerLimit\n\n\tif pStat.ID == 1 && chain > 1 {\n\t\tpStat.Time = pStat.Time + blockSyncMax + blockSyncMin + TimeSecond\n\t} else {\n\t\tpStat.Time += blockInterval\n\t}\n\n\tout.Previous = pStat.Key\n\tout.Producer = producer\n\tout.Time = pStat.Time\n\n\tout.Chain = chain\n\tout.Index = pStat.ID + 1\n\n\tif pStat.Chain > 1 {\n\t\tvar key Hash\n\t\tvar tmp BlockInfo\n\t\tgetDataFormLog(chain/2, logBlockInfo{}, runtime.Encode(pStat.ParentID+1), &key)\n\t\tgetDataFormLog(chain/2, logBlockInfo{}, key[:], &tmp)\n\t\tif out.Index != 2 && !key.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\tvar key2 Hash\n\t\t\tgetDataFormLog(chain/2, logBlockInfo{}, runtime.Encode(pStat.ParentID+2), &key2)\n\t\t\tgetDataFormLog(chain/2, logBlockInfo{}, key2[:], &tmp)\n\t\t\tif !key2.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\t\tout.Parent = key2\n\t\t\t} else {\n\t\t\t\tout.Parent = key\n\t\t\t}\n\t\t\t// assert(out.Time-tmp.Time <= blockSyncMax)\n\t\t} else {\n\t\t\tgetDataFormLog(chain/2, logBlockInfo{}, runtime.Encode(pStat.ParentID), &key)\n\t\t\tout.Parent = key\n\t\t}\n\t}\n\tif pStat.LeftChildID > 0 {\n\t\tvar key Hash\n\t\tvar tmp BlockInfo\n\t\tgetDataFormLog(2*chain, logBlockInfo{}, runtime.Encode(pStat.LeftChildID+1), &key)\n\t\tgetDataFormLog(2*chain, logBlockInfo{}, key[:], &tmp)\n\t\tif !key.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\tvar key2 Hash\n\t\t\tgetDataFormLog(2*chain, logBlockInfo{}, runtime.Encode(pStat.LeftChildID+2), &key2)\n\t\t\tgetDataFormLog(2*chain, logBlockInfo{}, key2[:], &tmp)\n\t\t\tif !key2.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\t\tout.LeftChild = key2\n\t\t\t} else {\n\t\t\t\tout.LeftChild = key\n\t\t\t}\n\t\t\t// assert(out.Time-tmp.Time <= blockSyncMax)\n\t\t} else if pStat.LeftChildID == 1 {\n\t\t\tgetDataFormLog(chain, logBlockInfo{}, runtime.Encode(pStat.LeftChildID), &key)\n\t\t\tout.LeftChild = key\n\t\t} else {\n\t\t\tgetDataFormLog(2*chain, logBlockInfo{}, runtime.Encode(pStat.LeftChildID), &key)\n\t\t\tout.LeftChild = key\n\t\t}\n\t}\n\tif pStat.RightChildID > 0 {\n\t\tvar key Hash\n\t\tvar tmp BlockInfo\n\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, runtime.Encode(pStat.RightChildID+1), &key)\n\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, key[:], &tmp)\n\t\tif !key.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\tvar key2 Hash\n\t\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, runtime.Encode(pStat.RightChildID+2), &key2)\n\t\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, key2[:], &tmp)\n\t\t\tif !key2.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\t\tout.RightChild = key2\n\t\t\t} else {\n\t\t\t\tout.RightChild = key\n\t\t\t}\n\t\t\t// assert(out.Time-tmp.Time <= blockSyncMax)\n\t\t} else if pStat.RightChildID == 1 {\n\t\t\tgetDataFormLog(chain, logBlockInfo{}, runtime.Encode(pStat.RightChildID), &key)\n\t\t\tout.RightChild = key\n\t\t} else {\n\t\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, runtime.Encode(pStat.RightChildID), &key)\n\t\t\tout.RightChild = key\n\t\t}\n\t}\n\n\treturn out\n}", "func generateNewBlock(oldBlock Block, dataPayload string) (Block, error) {\n\n\tvar newBlock Block\n\ttimeNow := time.Now()\n\n\tnewBlock.Index = oldBlock.Index + 1\n\tnewBlock.Timestamp = timeNow.String()\n\n\tnewEvent, err := dataPayloadtoServiceEvent(dataPayload)\n\n\tif err != nil {\n\t\tlog.Println(\"ERROR: Unable to convert data payload into ServiceEvent for new block generation.\")\n\t}\n\n\tnewBlock.Event = newEvent\n\tnewBlock.PrevHash = oldBlock.Hash\n\tnewBlock.Hash = calculateHash(newBlock)\n\n\treturn newBlock, nil\n}", "func newBlockstoreManager(bs bstore.Blockstore, workerCount int) *blockstoreManager {\n\treturn &blockstoreManager{\n\t\tbs: bs,\n\t\tworkerCount: workerCount,\n\t\tjobs: make(chan func()),\n\t}\n}", "func NewBlockWriter(rand io.Reader, orgId, streamId uuid.UUID, salt crypto.Salt, pass []byte, cipher crypto.Cipher) BlockWriter {\n\tidx, key := 0, salt.Apply(pass, cipher.KeySize())\n\treturn BlockWriterFn(func(data []byte) (next secret.Block, err error) {\n\t\tdefer func() {\n\t\t\tidx++\n\t\t}()\n\n\t\tct, err := cipher.Apply(rand, key, data)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tnext = secret.Block{orgId, streamId, idx, ct}\n\t\treturn\n\t})\n}", "func (*blockR) NewStruct() *blockR {\n\treturn &blockR{}\n}", "func NewBlock(header *Header, txs []*Transaction, receipts []*Receipt, signs []*PbftSign) *Block {\n\tb := &Block{header: CopyHeader(header)}\n\n\t// TODO: panic if len(txs) != len(receipts)\n\tif len(txs) == 0 {\n\t\tb.header.TxHash = EmptyRootHash\n\t} else {\n\t\tb.header.TxHash = DeriveSha(Transactions(txs))\n\t\tb.transactions = make(Transactions, len(txs))\n\t\tcopy(b.transactions, txs)\n\t}\n\n\tif len(receipts) == 0 {\n\t\tb.header.ReceiptHash = EmptyRootHash\n\t} else {\n\t\tb.header.ReceiptHash = DeriveSha(Receipts(receipts))\n\t\tb.header.Bloom = CreateBloom(receipts)\n\t}\n\n\tif len(receipts) == 0 {\n\t\tb.header.ReceiptHash = EmptyRootHash\n\t} else {\n\t\tb.header.ReceiptHash = DeriveSha(Receipts(receipts))\n\t\tb.header.Bloom = CreateBloom(receipts)\n\t}\n\n\tif len(signs) != 0 {\n\t\tb.signs = make(PbftSigns, len(signs))\n\t\tcopy(b.signs, signs)\n\t}\n\n\treturn b\n}", "func NewBlockRetriever(\n\topts BlockRetrieverOptions,\n\tfsOpts Options,\n) BlockRetriever {\n\tsegmentReaderPool := opts.SegmentReaderPool()\n\treqPoolOpts := opts.RequestPoolOptions()\n\treqPool := newRetrieveRequestPool(segmentReaderPool, reqPoolOpts)\n\treqPool.Init()\n\treturn &blockRetriever{\n\t\topts: opts,\n\t\tfsOpts: fsOpts,\n\t\tnewSeekerMgrFn: NewSeekerManager,\n\t\treqPool: reqPool,\n\t\tbytesPool: opts.BytesPool(),\n\t\tstatus: blockRetrieverNotOpen,\n\t\tnotifyFetch: make(chan struct{}, 1),\n\t}\n}", "func (w *Writer) newBlockWriter(typ byte) *blockWriter {\n\tblock := w.block\n\n\tvar blockStart uint32\n\tif w.next == 0 {\n\t\thb := w.headerBytes()\n\t\tblockStart = uint32(copy(block, hb))\n\t}\n\n\tbw := newBlockWriter(typ, block, blockStart)\n\tbw.restartInterval = w.opts.RestartInterval\n\treturn bw\n}", "func (ts *Tipset) Block(miner Miner, winCount int64, msgs ...*ApplicableMessage) {\n\tblock := Block{\n\t\tMinerAddr: miner.MinerActorAddr.ID,\n\t\tWinCount: winCount,\n\t}\n\tfor _, am := range msgs {\n\t\tblock.Messages = append(block.Messages, MustSerialize(am.Message))\n\n\t\t// if we see this message for the first time, add it to the `msgIdx` map and to the `orderMsgs` slice.\n\t\tif _, ok := ts.tss.msgIdx[am.Message.Cid()]; !ok {\n\t\t\tts.tss.msgIdx[am.Message.Cid()] = am\n\t\t\tts.tss.orderedMsgs = append(ts.tss.orderedMsgs, am)\n\t\t}\n\t}\n\n\tts.Blocks = append(ts.Blocks, block)\n}", "func NewBeeLister(indexer cache.Indexer) BeeLister {\n\treturn &beeLister{indexer: indexer}\n}", "func newBlockImporter(db database.DB, r io.ReadSeeker) (*blockImporter, error) {\n\t// Create the transaction and address indexes if needed.\n\t//\n\t// CAUTION: the txindex needs to be first in the indexes array because\n\t// the addrindex uses data from the txindex during catchup. If the\n\t// addrindex is run first, it may not have the transactions from the\n\t// current block indexed.\n\tvar indexes []indexers.Indexer\n\tif cfg.TxIndex || cfg.AddrIndex {\n\t\t// Enable transaction index if address index is enabled since it\n\t\t// requires it.\n\t\tif !cfg.TxIndex {\n\t\t\tlog.Infof(\"Transaction index enabled because it is \" +\n\t\t\t\t\"required by the address index\")\n\t\t\tcfg.TxIndex = true\n\t\t} else {\n\t\t\tlog.Info(\"Transaction index is enabled\")\n\t\t}\n\t\tindexes = append(indexes, indexers.NewTxIndex(db))\n\t}\n\tif cfg.AddrIndex {\n\t\tlog.Info(\"Address index is enabled\")\n\t\tindexes = append(indexes, indexers.NewAddrIndex(db, activeNetParams))\n\t}\n\n\t// Create an index manager if any of the optional indexes are enabled.\n\tvar indexManager blockchain.IndexManager\n\tif len(indexes) > 0 {\n\t\tindexManager = indexers.NewManager(db, indexes)\n\t}\n\n\tchain, err := blockchain.New(&blockchain.Config{\n\t\tDB: db,\n\t\tChainParams: activeNetParams,\n\t\tTimeSource: blockchain.NewMedianTime(),\n\t\tIndexManager: indexManager,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &blockImporter{\n\t\tdb: db,\n\t\tr: r,\n\t\tprocessQueue: make(chan []byte, 2),\n\t\tdoneChan: make(chan bool),\n\t\terrChan: make(chan error),\n\t\tquit: make(chan struct{}),\n\t\tchain: chain,\n\t\tlastLogTime: time.Now(),\n\t}, nil\n}", "func NewBlock(data string, transactions []*Tx, prevBlockHash []byte) *Block {\n\tblock := &Block{\n\t\tIdentifier: internal.GenerateID(),\n\t\tData: []byte(data),\n\t\tTransactions: transactions,\n\t\tPrevBlockHash: prevBlockHash,\n\t\tTimestamp: time.Now().Unix(),\n\t}\n\n\tpow := NewPow(block)\n\tnonce, hash := pow.Run()\n\n\tblock.Hash = hash[:]\n\tblock.Nonce = nonce\n\treturn block\n}", "func newBlock(prevHash [32]byte, prevHashWithoutTx [32]byte, commitmentProof [crypto.COMM_PROOF_LENGTH]byte, height uint32) *protocol.Block {\n\tblock := new(protocol.Block)\n\tblock.PrevHash = prevHash\n\tblock.PrevHashWithoutTx = prevHashWithoutTx\n\tblock.CommitmentProof = commitmentProof\n\tblock.Height = height\n\tblock.StateCopy = make(map[[32]byte]*protocol.Account)\n\tblock.Aggregated = false\n\n\treturn block\n}", "func NewBlock(transactions []*Transaction, preBlockHash []byte) *Block {\n\tb := &Block{time.Now().Unix(), transactions, preBlockHash, []byte{}, 252, 0}\n\n\tpow := NewProofOfWork(b)\n\tnonce, hash := pow.Run()\n\n\tb.Nonce = nonce\n\tb.Hash = hash[:]\n\n\treturn b\n}", "func NewBlock(width float64, height float64) *Block {\n\tb := &Block{}\n\tb.contents = &contentstream.ContentStreamOperations{}\n\tb.resources = model.NewPdfPageResources()\n\tb.width = width\n\tb.height = height\n\treturn b\n}", "func NewBlock(seqNum uint64, previousHash []byte) *cb.Block {\n\tblock := &cb.Block{}\n\tblock.Header = &cb.BlockHeader{}\n\tblock.Header.Number = seqNum\n\tblock.Header.PreviousHash = previousHash\n\tblock.Header.DataHash = []byte{}\n\tblock.Data = &cb.BlockData{}\n\n\tvar metadataContents [][]byte\n\tfor i := 0; i < len(cb.BlockMetadataIndex_name); i++ {\n\t\tmetadataContents = append(metadataContents, []byte{})\n\t}\n\tblock.Metadata = &cb.BlockMetadata{Metadata: metadataContents}\n\n\treturn block\n}", "func New(workers *workerpool.Group, evictionState *eviction.State, slotTimeProviderFunc func() *slot.TimeProvider, latestCommitmentFunc func(slot.Index) (*commitment.Commitment, error), opts ...options.Option[BlockDAG]) (newBlockDAG *BlockDAG) {\n\treturn options.Apply(&BlockDAG{\n\t\tevents: blockdag.NewEvents(),\n\t\tevictionState: evictionState,\n\t\tslotTimeProviderFunc: slotTimeProviderFunc,\n\t\tmemStorage: memstorage.NewSlotStorage[models.BlockID, *blockdag.Block](),\n\t\tcommitmentFunc: latestCommitmentFunc,\n\t\tfutureBlocks: memstorage.NewSlotStorage[commitment.ID, *advancedset.AdvancedSet[*blockdag.Block]](),\n\t\tWorkers: workers,\n\t\t// do not use workerpool to make sure things run synchronously\n\t\t//workerPool: workers.CreatePool(\"Solidifier\", 2),\n\n\t}, opts,\n\t\tfunc(b *BlockDAG) {\n\t\t\tb.solidifier = causalordersync.New(\n\t\t\t\tb.workerPool,\n\t\t\t\tb.Block,\n\t\t\t\t(*blockdag.Block).IsSolid,\n\t\t\t\tb.markSolid,\n\t\t\t\tb.markInvalid,\n\t\t\t\t(*blockdag.Block).Parents,\n\t\t\t\tcausalordersync.WithReferenceValidator[models.BlockID](checkReference),\n\t\t\t)\n\n\t\t\tevictionState.Events.SlotEvicted.Hook(b.evictSlot /*, event.WithWorkerPool(b.workerPool)*/)\n\t\t},\n\t\t(*BlockDAG).TriggerConstructed,\n\t\t(*BlockDAG).TriggerInitialized,\n\t)\n}", "func (c *Client) Block() *Block {\n\treturn &Block{c}\n}", "func NewBlockchain() (*Blockchain, error) {\n\tdb, rel, err := OpenBlockChain()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, err = db.Get([]byte(\"l\"), nil)\n\tif err == leveldb.ErrNotFound {\n\t\tb := Blockchain{}\n\t\tgenesis := GenesisBlock()\n\t\t//TODO: use add block instead\n\t\tb.Tip = genesis\n\t\tb.GenesisHash = genesis.Hash\n\t\traw, _ := proto.Marshal(genesis)\n\t\terr = db.Put(\n\t\t\tbytes.Join([][]byte{\n\t\t\t\t[]byte(\"b\"), genesis.Hash}, []byte{}), raw, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = db.Put([]byte(\"l\"), genesis.Hash, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = rel.Put(genesis.Hash, []byte{}, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tb.DB = db\n\t\tb.Relation = rel\n\t\treturn &b, nil\n\t}\n\treturn nil, Consts.ErrBlockchainExists\n}", "func NewBlock(_data string, _prevHash []byte) *Block {\n\t_block := &Block{\n\t\tTimestamp: time.Now().Unix(),\n\t\tData: []byte(_data),\n\t\tPrevHash: _prevHash,\n\t\tHash: []byte{},\n\t}\n\n\tpow := NewProofOfWork(_block)\n\tnonce, hash := pow.Run()\n\n\t_block.Nonce = nonce\n\t_block.Hash = hash[:]\n\n\treturn _block\n}", "func newBlock(t nbt.Tag) BlockState {\r\n\tblock := BlockState{}\r\n\tblock.Name = t.Compound()[\"Name\"].String()\r\n\tblock.parseProperties(t)\r\n\treturn block\r\n}", "func NewTestBlocklist() *blocklist.Blocklist {\n\tlist := blocklist.New()\n\tlist.Name = \"test\"\n\tlist.Domains = []string{\"www.reddit.com\", \"news.ycombinator.com\"}\n\n\treturn list\n}", "func NewBlock(tlvType uint32, value []byte) *Block {\n\tvar block Block\n\tblock.tlvType = tlvType\n\tblock.value = value\n\t// copy(block.value, value)\n\treturn &block\n}", "func NewBlock(version uint32, prevBlock []byte, merkleRoot []byte, timestamp uint32, bits []byte, nonce []byte, txHashes [][]byte) *Block {\n\tblock := &Block{Version: version, Timestamp: timestamp}\n\tcopy(block.PrevBlock[:32], prevBlock)\n\tcopy(block.MerkleRoot[:32], merkleRoot)\n\tcopy(block.Bits[:4], bits)\n\tcopy(block.Nonce[:4], nonce)\n\tblock.TxHashes = txHashes\n\treturn block\n}", "func NewBlockCache(dbPath string, chainName string, startHeight int, syncFromHeight int) *BlockCache {\n\tc := &BlockCache{}\n\tc.firstBlock = startHeight\n\tc.nextBlock = startHeight\n\tc.lengthsName, c.blocksName = dbFileNames(dbPath, chainName)\n\tvar err error\n\tif err := os.MkdirAll(filepath.Join(dbPath, chainName), 0755); err != nil {\n\t\tLog.Fatal(\"mkdir \", dbPath, \" failed: \", err)\n\t}\n\tc.blocksFile, err = os.OpenFile(c.blocksName, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0644)\n\tif err != nil {\n\t\tLog.Fatal(\"open \", c.blocksName, \" failed: \", err)\n\t}\n\tc.lengthsFile, err = os.OpenFile(c.lengthsName, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0644)\n\tif err != nil {\n\t\tLog.Fatal(\"open \", c.lengthsName, \" failed: \", err)\n\t}\n\tlengths, err := ioutil.ReadFile(c.lengthsName)\n\tif err != nil {\n\t\tLog.Fatal(\"read \", c.lengthsName, \" failed: \", err)\n\t}\n\t// 4 bytes per lengths[] value (block length)\n\tif syncFromHeight >= 0 {\n\t\tif syncFromHeight < startHeight {\n\t\t\tsyncFromHeight = startHeight\n\t\t}\n\t\tif (syncFromHeight-startHeight)*4 < len(lengths) {\n\t\t\t// discard the entries at and beyond (newer than) the specified height\n\t\t\tlengths = lengths[:(syncFromHeight-startHeight)*4]\n\t\t}\n\t}\n\n\t// The last entry in starts[] is where to write the next block.\n\tvar offset int64\n\tc.starts = nil\n\tc.starts = append(c.starts, 0)\n\tnBlocks := len(lengths) / 4\n\tLog.Info(\"Reading \", nBlocks, \" blocks (since Sapling activation) from disk cache ...\")\n\tfor i := 0; i < nBlocks; i++ {\n\t\tif len(lengths[:4]) < 4 {\n\t\t\tLog.Warning(\"lengths file has a partial entry\")\n\t\t\tc.recoverFromCorruption(c.nextBlock)\n\t\t\tbreak\n\t\t}\n\t\tlength := binary.LittleEndian.Uint32(lengths[i*4 : (i+1)*4])\n\t\tif length < 74 || length > 4*1000*1000 {\n\t\t\tLog.Warning(\"lengths file has impossible value \", length)\n\t\t\tc.recoverFromCorruption(c.nextBlock)\n\t\t\tbreak\n\t\t}\n\t\toffset += int64(length) + 8\n\t\tc.starts = append(c.starts, offset)\n\t\t// Check for corruption.\n\t\tblock := c.readBlock(c.nextBlock)\n\t\tif block == nil {\n\t\t\tLog.Warning(\"error reading block\")\n\t\t\tc.recoverFromCorruption(c.nextBlock)\n\t\t\tbreak\n\t\t}\n\t\tc.nextBlock++\n\t}\n\tc.setDbFiles(c.nextBlock)\n\tLog.Info(\"Done reading \", c.nextBlock-c.firstBlock, \" blocks from disk cache\")\n\treturn c\n}", "func NewBlock(\n\tblockStart xtime.UnixNano,\n\tmd namespace.Metadata,\n\tblockOpts BlockOptions,\n\tnamespaceRuntimeOptsMgr namespace.RuntimeOptionsManager,\n\topts Options,\n) (Block, error) {\n\tblockSize := md.Options().IndexOptions().BlockSize()\n\tiopts := opts.InstrumentOptions()\n\tscope := iopts.MetricsScope().SubScope(\"index\").SubScope(\"block\")\n\tiopts = iopts.SetMetricsScope(scope)\n\n\tcpus := int(math.Max(1, math.Ceil(0.25*float64(runtime.GOMAXPROCS(0)))))\n\tcachedSearchesWorkers := xsync.NewWorkerPool(cpus)\n\tcachedSearchesWorkers.Init()\n\n\tsegs := newMutableSegments(\n\t\tmd,\n\t\tblockStart,\n\t\topts,\n\t\tblockOpts,\n\t\tcachedSearchesWorkers,\n\t\tnamespaceRuntimeOptsMgr,\n\t\tiopts,\n\t)\n\n\tcoldSegs := newMutableSegments(\n\t\tmd,\n\t\tblockStart,\n\t\topts,\n\t\tblockOpts,\n\t\tcachedSearchesWorkers,\n\t\tnamespaceRuntimeOptsMgr,\n\t\tiopts,\n\t)\n\n\t// NB(bodu): The length of coldMutableSegments is always at least 1.\n\tcoldMutableSegments := []*mutableSegments{coldSegs}\n\tb := &block{\n\t\tstate: blockStateOpen,\n\t\tblockStart: blockStart,\n\t\tblockEnd: blockStart.Add(blockSize),\n\t\tblockSize: blockSize,\n\t\tblockOpts: blockOpts,\n\t\tcachedSearchesWorkers: cachedSearchesWorkers,\n\t\tmutableSegments: segs,\n\t\tcoldMutableSegments: coldMutableSegments,\n\t\tshardRangesSegmentsByVolumeType: make(shardRangesSegmentsByVolumeType),\n\t\topts: opts,\n\t\tiopts: iopts,\n\t\tnsMD: md,\n\t\tnamespaceRuntimeOptsMgr: namespaceRuntimeOptsMgr,\n\t\tmetrics: newBlockMetrics(scope),\n\t\tlogger: iopts.Logger(),\n\t\tfetchDocsLimit: opts.QueryLimits().FetchDocsLimit(),\n\t\taggDocsLimit: opts.QueryLimits().AggregateDocsLimit(),\n\t}\n\tb.newFieldsAndTermsIteratorFn = newFieldsAndTermsIterator\n\tb.newExecutorWithRLockFn = b.executorWithRLock\n\tb.addAggregateResultsFn = b.addAggregateResults\n\n\treturn b, nil\n}", "func NewMockAergoRPCService_ListBlockStreamServer(ctrl *gomock.Controller) *MockAergoRPCService_ListBlockStreamServer {\n\tmock := &MockAergoRPCService_ListBlockStreamServer{ctrl: ctrl}\n\tmock.recorder = &MockAergoRPCService_ListBlockStreamServerMockRecorder{mock}\n\treturn mock\n}", "func New(api API) *LotusChain {\n\treturn &LotusChain{\n\t\tapi: api,\n\t}\n}", "func NewBlock(filename string, blockNum int) *Block {\n\treturn &Block{FileName: filename, BlockNum: blockNum}\n}", "func NewBlockWriter(block *hdfs.LocatedBlockProto, namenode *NamenodeConnection, blockSize int64) *BlockWriter {\n\tpm := newPipelineManager(namenode, block)\n\n\ts := &BlockWriter{\n\t\tpm: pm,\n\t\tblock: block,\n\t\tblockSize: blockSize,\n\t}\n\n\treturn s\n}", "func NewBlock(prev Block, currentTime uint64, uxHash cipher.SHA256, txns Transactions, calc FeeCalculator) (*Block, error) {\n\tif len(txns) == 0 {\n\t\treturn nil, fmt.Errorf(\"Refusing to create block with no transactions\")\n\t}\n\n\tfee, err := txns.Fees(calc)\n\tif err != nil {\n\t\t// This should have been caught earlier\n\t\treturn nil, fmt.Errorf(\"Invalid transaction fees: %v\", err)\n\t}\n\n\tbody := BlockBody{txns}\n\thead := NewBlockHeader(prev.Head, uxHash, currentTime, fee, body)\n\treturn &Block{\n\t\tHead: head,\n\t\tBody: body,\n\t}, nil\n}", "func NewBlock(data string, prevBlockHash []byte) *Block {\n\tblock := &Block{time.Now().Unix(), []byte(data), prevBlockHash, []byte{}, 0}\n\tpow := NewProofOfWork(block)\n\n\tnonce, hash := pow.Run()\n\n\tblock.Hash = hash[:]\n\tblock.Nonce = nonce\n\n\treturn block\n}", "func New(cfg *config.Config, hub *component.ComponentHub) (*SimpleBlockFactory, error) {\n\tconsensus.InitBlockInterval(cfg.Consensus.BlockInterval)\n\n\ts := &SimpleBlockFactory{\n\t\tComponentHub: hub,\n\t\tjobQueue: make(chan interface{}, slotQueueMax),\n\t\tblockInterval: consensus.BlockInterval,\n\t\tmaxBlockBodySize: chain.MaxBlockBodySize(),\n\t\tquit: make(chan interface{}),\n\t}\n\n\ts.txOp = chain.NewCompTxOp(\n\t\tchain.TxOpFn(func(txIn *types.Tx) (*types.BlockState, error) {\n\t\t\tselect {\n\t\t\tcase <-s.quit:\n\t\t\t\treturn nil, chain.ErrQuit\n\t\t\tdefault:\n\t\t\t\treturn nil, nil\n\t\t\t}\n\t\t}),\n\t)\n\n\treturn s, nil\n}", "func (s *SimpleBlockFactory) BlockFactory() consensus.BlockFactory {\n\treturn s\n}", "func NewBlock(prev Block, currentTime uint64, uxHash cipher.SHA256, txns Transactions, calc FeeCalculator) (*Block, error) {\n\tif len(txns) == 0 {\n\t\treturn nil, fmt.Errorf(\"Refusing to create block with no transactions\")\n\t}\n\n\tfee, err := txns.Fees(calc)\n\tif err != nil {\n\t\t// This should have been caught earlier\n\t\treturn nil, fmt.Errorf(\"Invalid transaction fees: %v\", err)\n\t}\n\n\tbody := BlockBody{txns}\n\treturn &Block{\n\t\tHead: NewBlockHeader(prev.Head, uxHash, currentTime, fee, body),\n\t\tBody: body,\n\t}, nil\n}", "func NewBlock(previousBlock Block, data string) (Block, error) {\n\tvar newBlock Block\n\n\tnewBlock.Index = previousBlock.Index + 1\n\tnewBlock.Timestamp = time.Now().String()\n\tnewBlock.Data = data\n\tnewBlock.PrevHash = previousBlock.Hash\n\tnewBlock.Difficulty = GetDifficulty()\n\n\tif !isCandidateBlockValid(newBlock, previousBlock) {\n\t\treturn newBlock, errors.New(\"Candidate block is not valid\")\n\t}\n\n\tmineBlock(&newBlock)\n\n\treturn newBlock, nil\n}", "func NewBlockHandler(cfg Config, m mesh, v blockValidator, lg log.Log) *BlockHandler {\n\treturn &BlockHandler{\n\t\tLog: lg,\n\t\ttraverse: m.ForBlockInView,\n\t\tdepth: cfg.Depth,\n\t\tmesh: m,\n\t\tvalidator: v,\n\t\tgoldenATXID: cfg.GoldenATXID,\n\t}\n}", "func (b *Block) List(input *BlockCursorInput) (*Blocks, error) {\n\tparams := make(map[string]string)\n\tparams[\"cursor\"] = input.Cursor\n\tresp, err := b.c.Request(http.MethodGet, \"/blocks\", new(bytes.Buffer), params)\n\tif err != nil {\n\t\treturn &Blocks{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar blocks *Blocks\n\terr = json.NewDecoder(resp.Body).Decode(&blocks)\n\tif err != nil {\n\t\treturn &Blocks{}, err\n\t}\n\treturn blocks, nil\n}", "func NewBlock(data string, prevBlockHash []byte) *Block {\n\tblock := &Block{\n\t\tTimestamp: time.Now().Unix(),\n\t\tData: []byte(data),\n\t\tPrevBlockHash: prevBlockHash,\n\t\tHash: []byte{},\n\t}\n\tpow := NewProofOfWork(block)\n\tnonce, hash := pow.Run()\n\n\tblock.Hash = hash[:]\n\tblock.Nonce = nonce\n\n\treturn block\n}", "func NewBlockChain(address string) *BlockChain {\n\t//return \t&BlockClain{\n\t//\t[]*Block{genesisBlock},\n\t//}\n\n\tvar lastHash []byte\n\tdb, err := bolt.Open(BlockChainDB, 0600, nil)\n\t//defer db.Close()\n\tif err != nil {\n\t\tlog.Fatal(\"create database failed\")\n\t}\n\terr = db.Update(func(tx *bolt.Tx) error {\n\t\tbucket := tx.Bucket([]byte(BlockBucket))\n\t\tif bucket == nil{\n\t\t\tbucket,err = tx.CreateBucket([]byte(BlockBucket))\n\t\t\tif err != nil{\n\t\t\t\tlog.Fatal(\"create bucket failed\")\n\t\t\t}\n\n\t\t\t//Create genesis block\n\t\t\tgenesisBlock := GenesisBlock(address)\n\n\t\t\t//Write message into database\n\t\t\tbucket.Put(genesisBlock.Hash,genesisBlock.Serialize())\n\t\t\tbucket.Put([]byte(\"LastHashKey\"),genesisBlock.Hash)\n\t\t\tlastHash = genesisBlock.Hash\n\t\t}else{\n\t\t\tlastHash = bucket.Get([]byte(\"LastHashKey\"))\n\t\t}\n\n\t\treturn nil\n\t})\n\treturn &BlockChain{db,lastHash}\n}", "func NewBlock(data string, prevBlockHash []byte) *Block {\n\tblock := &Block{\n\t\tTimestamp: time.Now().UTC().Unix(),\n\t\tPrevBlockHash: prevBlockHash,\n\t\tHash: []byte{},\n\t\tData: []byte(data),\n\t}\n\n\tpow := NewProofOfWork(block)\n\tnonce, hash := pow.Run()\n\n\tblock.Hash = hash[:]\n\tblock.Nonce = nonce\n\n\treturn block\n}", "func NewLister(tableName string, selectedColumns []string) Lister {\n\treturn &universalLister{\n\t\ttableName: tableName,\n\t\tselectedColumns: strings.Join(selectedColumns, \", \"),\n\t\torderByParams: NoOrderBy,\n\t}\n}", "func (obj Events) Block() Block {\n\treturn Block(obj)\n}" ]
[ "0.6314954", "0.6238325", "0.6161388", "0.61283696", "0.5824281", "0.55151194", "0.520106", "0.51907414", "0.5156084", "0.5144187", "0.51403826", "0.5134927", "0.50486195", "0.5025212", "0.5025212", "0.5023222", "0.5006356", "0.49875388", "0.49786118", "0.49344215", "0.49330792", "0.49155775", "0.4910406", "0.49064437", "0.488934", "0.48796088", "0.48437902", "0.4824231", "0.4805415", "0.48010796", "0.47782475", "0.47504488", "0.4737139", "0.4730701", "0.47051713", "0.46741652", "0.46665058", "0.46619573", "0.46582708", "0.46582112", "0.46577087", "0.46451235", "0.463314", "0.46313232", "0.46253932", "0.461637", "0.46125263", "0.46013114", "0.46008408", "0.46002826", "0.45911735", "0.45746672", "0.4573626", "0.45578954", "0.45552456", "0.45517176", "0.45416215", "0.45379454", "0.45326343", "0.45104796", "0.45006105", "0.45003283", "0.44983888", "0.44842848", "0.44813633", "0.44685465", "0.44667336", "0.44618955", "0.44567356", "0.4453754", "0.44484168", "0.44450137", "0.44416794", "0.44373575", "0.44355655", "0.44280574", "0.44150883", "0.4406206", "0.43997657", "0.43975884", "0.43859822", "0.43806827", "0.43703875", "0.4362323", "0.43621016", "0.4359465", "0.43580246", "0.43485993", "0.43397093", "0.43391466", "0.4336746", "0.4333372", "0.43333033", "0.43309826", "0.43271306", "0.4321909", "0.4321051", "0.432026", "0.43069863", "0.4305192" ]
0.84841317
0
List lists all RolloutBlocks in the indexer.
Список отображает все RolloutBlocks в индексаторе.
func (s *rolloutBlockLister) List(selector labels.Selector) (ret []*v1alpha1.RolloutBlock, err error) { err = cache.ListAll(s.indexer, selector, func(m interface{}) { ret = append(ret, m.(*v1alpha1.RolloutBlock)) }) return ret, err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s rolloutBlockNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.RolloutBlock, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.RolloutBlock))\n\t})\n\treturn ret, err\n}", "func (s *rolloutBlockLister) RolloutBlocks(namespace string) RolloutBlockNamespaceLister {\n\treturn rolloutBlockNamespaceLister{indexer: s.indexer, namespace: namespace}\n}", "func NewRolloutBlockLister(indexer cache.Indexer) RolloutBlockLister {\n\treturn &rolloutBlockLister{indexer: indexer}\n}", "func (s *Server) List(ctx context.Context, in *proto.GetBlockRequest) (*proto.GetBlockResponse, error) {\n\ti, err := metrics.Gauge(\"List\", func() (interface{}, error) {\n\t\tresp := new(proto.GetBlockResponse)\n\n\t\tfor _, b := range s.Blockchain.Blocks {\n\t\t\tresp.Blocks = append(resp.Blocks, &proto.Block{\n\t\t\t\tPrevBlockHash: b.PrevBlockHash,\n\t\t\t\tData: b.Data,\n\t\t\t\tHash: b.Hash,\n\t\t\t})\n\t\t}\n\n\t\treturn resp, nil\n\t})\n\treturn i.(*proto.GetBlockResponse), err\n}", "func (b *Block) List(input *BlockCursorInput) (*Blocks, error) {\n\tparams := make(map[string]string)\n\tparams[\"cursor\"] = input.Cursor\n\tresp, err := b.c.Request(http.MethodGet, \"/blocks\", new(bytes.Buffer), params)\n\tif err != nil {\n\t\treturn &Blocks{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar blocks *Blocks\n\terr = json.NewDecoder(resp.Body).Decode(&blocks)\n\tif err != nil {\n\t\treturn &Blocks{}, err\n\t}\n\treturn blocks, nil\n}", "func (a *DefaultClient) List(l vfs.Location) ([]string, error) {\n\tURL, err := url.Parse(l.(*Location).ContainerURL())\n\tif err != nil {\n\t\treturn []string{}, err\n\t}\n\n\tcontainerURL := azblob.NewContainerURL(*URL, a.pipeline)\n\tctx := context.Background()\n\tvar list []string\n\tfor marker := (azblob.Marker{}); marker.NotDone(); {\n\t\tlistBlob, err := containerURL.ListBlobsHierarchySegment(ctx, marker, \"/\",\n\t\t\tazblob.ListBlobsSegmentOptions{Prefix: utils.RemoveLeadingSlash(l.Path())})\n\t\tif err != nil {\n\t\t\treturn []string{}, err\n\t\t}\n\n\t\tmarker = listBlob.NextMarker\n\n\t\tfor i := range listBlob.Segment.BlobItems {\n\t\t\tlist = append(list, listBlob.Segment.BlobItems[i].Name)\n\t\t}\n\t}\n\treturn list, nil\n}", "func (s *BlockService) List(limit int, cursor string) (models.BlockPage, error) {\n\tif limit > 100 {\n\t\tlimit = 100\n\t}\n\tif limit == 0 {\n\t\tlimit = 10\n\t}\n\treturn s.dao.Find(bson.M{}, limit, cursor)\n}", "func (s rolloutBlockNamespaceLister) Get(name string) (*v1alpha1.RolloutBlock, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"rolloutblock\"), name)\n\t}\n\treturn obj.(*v1alpha1.RolloutBlock), nil\n}", "func (c *BlockVolumeClient) List(params *BlockVolumeParams) (*BlockVolumeList, error) {\n\tlist := &BlockVolumeList{}\n\n\terr := c.Backend.CallIntoInterface(\"v1/Storage/Block/Volume/list\", params, list)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn list, nil\n}", "func Blocks(offset, count uint) ([]BlockItem, error) {\n\tjsonBlocks := []struct {\n\t\tNumber uint `json:\"number\"`\n\t\tHash string `json:\"hash\"`\n\t\tDate Time `json:\"date\"`\n\t\tDifficulty uint64 `json:\"difficulty\"`\n\t\tMiner string `json:\"miner\"`\n\t}{}\n\tif err := fetch(&jsonBlocks, blockEndpoint, offset, count); err != nil {\n\t\treturn nil, err\n\t}\n\tblocks := make([]BlockItem, len(jsonBlocks))\n\tfor i, b := range jsonBlocks {\n\t\tblocks[i] = BlockItem(b)\n\t}\n\treturn blocks, nil\n}", "func (l *LessonTut) Blocks() []*BlockTut { return l.blocks }", "func (s *bundleLister) List(selector labels.Selector) (ret []*v1alpha1.Bundle, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.Bundle))\n\t})\n\treturn ret, err\n}", "func (s *wafregionalRuleLister) List(selector labels.Selector) (ret []*v1alpha1.WafregionalRule, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.WafregionalRule))\n\t})\n\treturn ret, err\n}", "func (b *indexBlock) Blocks() ([]blockHandle, error) {\n\tvar lastKey []byte\n\tkb := make([]byte, 0, MaxSstKeySize)\n\tvar blocks []blockHandle\n\n\tfor b.r.Len() > 0 {\n\t\teKey, err := prefixDecodeFrom(b.r, lastKey, kb)\n\t\tlastKey = eKey\n\t\tif _, err := binary.ReadUvarint(b.r); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbh, err := newBlockHandle(b.r)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tblocks = append(blocks, bh)\n\t}\n\n\treturn blocks, nil\n}", "func (c *MockLoadBalancersClient) List(ctx context.Context, resourceGroupName string) ([]network.LoadBalancer, error) {\n\tvar l []network.LoadBalancer\n\tfor _, lb := range c.LBs {\n\t\tl = append(l, lb)\n\t}\n\treturn l, nil\n}", "func printBlockList(blobClient *storage.BlobStorageClient, containerName, blockBlobName string) error {\n\tfmt.Println(\"Get block list...\")\n\tlist, err := blobClient.GetBlockList(containerName, blockBlobName, storage.BlockListTypeAll)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Printf(\"Block blob '%v' block list\\n\", blockBlobName)\n\tfmt.Println(\"\\tCommitted Blocks' IDs\")\n\tfor _, b := range list.CommittedBlocks {\n\t\tfmt.Printf(\"\\t\\t%v\\n\", b.Name)\n\t}\n\tfmt.Println(\"\\tUncommited Blocks' IDs\")\n\tfor _, b := range list.UncommittedBlocks {\n\t\tfmt.Printf(\"\\t\\t%v\\n\", b.Name)\n\t}\n\treturn nil\n}", "func (h *Handler) List() ([]*unstructured.Unstructured, error) {\n\treturn h.ListAll()\n}", "func List(client *golangsdk.ServiceClient, clusterId string) (r ListResult) {\n\t_, r.Err = client.Get(listURL(client, clusterId), &r.Body, nil)\n\treturn\n}", "func (s bundleNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Bundle, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.Bundle))\n\t})\n\treturn ret, err\n}", "func (s beeNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.Bee, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.Bee))\n\t})\n\treturn ret, err\n}", "func (i *Index) List() List {\n\t// prepare list\n\tlist := make(List, 0, i.btree.Len())\n\n\t// walk index\n\ti.btree.Scan(func(item Doc) bool {\n\t\tlist = append(list, item)\n\t\treturn true\n\t})\n\n\treturn list\n}", "func (client Client) List() (result ListResult, err error) {\n\treq, err := client.ListPreparer()\n\tif err != nil {\n\t\treturn result, autorest.NewErrorWithError(err, \"redis.Client\", \"List\", nil, \"Failure preparing request\")\n\t}\n\n\tresp, err := client.ListSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\treturn result, autorest.NewErrorWithError(err, \"redis.Client\", \"List\", resp, \"Failure sending request\")\n\t}\n\n\tresult, err = client.ListResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"redis.Client\", \"List\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (s *hookLister) List(selector labels.Selector) (ret []*v1alpha1.Hook, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.Hook))\n\t})\n\treturn ret, err\n}", "func (c *ClusterResourceClient) List(ctx context.Context, opts metav1.ListOptions) (*metav1.PartialObjectMetadataList, error) {\n\treturn c.clientCache.ClusterOrDie(logicalcluster.Wildcard).Resource(c.resource).List(ctx, opts)\n}", "func (s hookNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Hook, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.Hook))\n\t})\n\treturn ret, err\n}", "func (api *snapshotrestoreAPI) List(ctx context.Context, opts *api.ListWatchOptions) ([]*SnapshotRestore, error) {\n\tvar objlist []*SnapshotRestore\n\tobjs, err := api.ct.List(\"SnapshotRestore\", 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 *SnapshotRestore:\n\t\t\teobj := obj.(*SnapshotRestore)\n\t\t\tobjlist = append(objlist, eobj)\n\t\tdefault:\n\t\t\tlog.Fatalf(\"Got invalid object type %v while looking for SnapshotRestore\", tp)\n\t\t}\n\t}\n\n\treturn objlist, nil\n}", "func (c *Client) List(ctx context.Context, p *ListPayload) (res *ListResult, err error) {\n\tvar ires interface{}\n\tires, err = c.ListEndpoint(ctx, p)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn ires.(*ListResult), nil\n}", "func (s *awsApiGatewayBasePathMappingLister) List(selector labels.Selector) (ret []*v1.AwsApiGatewayBasePathMapping, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.AwsApiGatewayBasePathMapping))\n\t})\n\treturn ret, err\n}", "func (c *MockRouteTablesClient) List(ctx context.Context, resourceGroupName string) ([]network.RouteTable, error) {\n\tvar l []network.RouteTable\n\tfor _, rt := range c.RTs {\n\t\tl = append(l, rt)\n\t}\n\treturn l, nil\n}", "func (c *Client) ListChangedBlocks(ctx context.Context, params *ListChangedBlocksInput, optFns ...func(*Options)) (*ListChangedBlocksOutput, error) {\n\tif params == nil {\n\t\tparams = &ListChangedBlocksInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"ListChangedBlocks\", params, optFns, addOperationListChangedBlocksMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*ListChangedBlocksOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func (r *RestService) List(relativeURL string, offset int64, limit int64) ([]byte, error) {\n\tqueryParams := fmt.Sprintf(\"?offset=%v&limit=%v\", offset, limit)\n\tfullURL := *r.Bitmovin.APIBaseURL + relativeURL + queryParams\n\n\treq, err := http.NewRequest(\"GET\", fullURL, nil)\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"X-Api-Key\", *r.Bitmovin.APIKey)\n\tif r.Bitmovin.OrganizationID != nil {\n\t\treq.Header.Set(\"X-Tenant-Org-Id\", *r.Bitmovin.OrganizationID)\n\t}\n\treq.Header.Set(\"X-Api-Client\", ClientName)\n\treq.Header.Set(\"X-Api-Client-Version\", Version)\n\n\tresp, err := r.Bitmovin.HTTPClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn body, nil\n}", "func (h *Handler) List() ([]*corev1.Node, error) {\n\treturn h.ListAll()\n}", "func (c *MockVirtualNetworksClient) List(ctx context.Context, resourceGroupName string) ([]network.VirtualNetwork, error) {\n\tvar l []network.VirtualNetwork\n\tfor _, vnet := range c.VNets {\n\t\tl = append(l, vnet)\n\t}\n\treturn l, nil\n}", "func (s *beeLister) List(selector labels.Selector) (ret []*v1beta1.Bee, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.Bee))\n\t})\n\treturn ret, err\n}", "func BlockAll(ctx context.Context) schema.Block {\n\treturn Block(ctx, Opts{\n\t\tCreate: true,\n\t\tRead: true,\n\t\tUpdate: true,\n\t\tDelete: true,\n\t})\n}", "func BlockStats(offset, count uint) ([]BlockStatItem, error) {\n\tjsonStats := []struct {\n\t\tDate Time `json:\"date\"`\n\t\tDifficulty uint64 `json:\"difficulty\"`\n\t\tBlockTime float64 `json:\"block_time\"`\n\t}{}\n\tif err := fetch(&jsonStats, blockStatsEndpoint, offset, count); err != nil {\n\t\treturn nil, err\n\t}\n\tstats := make([]BlockStatItem, len(jsonStats))\n\tfor i, s := range jsonStats {\n\t\tstats[i] = BlockStatItem(s)\n\t}\n\treturn stats, nil\n}", "func (_PlasmaFramework *PlasmaFrameworkSession) Blocks(arg0 *big.Int) (struct {\n\tRoot [32]byte\n\tTimestamp *big.Int\n}, error) {\n\treturn _PlasmaFramework.Contract.Blocks(&_PlasmaFramework.CallOpts, arg0)\n}", "func (tt *BlockTestTable) GetAll() []TypedBlock {\n\tvar result []TypedBlock\n\tfor _, b := range tt.AccountBlocks {\n\t\tresult = append(result, TypedBlock{\n\t\t\tAccountBlock: b,\n\t\t\tT: \"account\",\n\t\t})\n\t}\n\tfor _, b := range tt.SwapBlocks {\n\t\tresult = append(result, TypedBlock{\n\t\t\tSwapBlock: b,\n\t\t\tT: \"swap\",\n\t\t})\n\t}\n\tfor _, b := range tt.OrderBlocks {\n\t\tresult = append(result, TypedBlock{\n\t\t\tOrderBlock: b,\n\t\t\tT: \"order\",\n\t\t})\n\t}\n\treturn result\n}", "func (api *configurationsnapshotAPI) List(ctx context.Context, opts *api.ListWatchOptions) ([]*ConfigurationSnapshot, error) {\n\tvar objlist []*ConfigurationSnapshot\n\tobjs, err := api.ct.List(\"ConfigurationSnapshot\", 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 *ConfigurationSnapshot:\n\t\t\teobj := obj.(*ConfigurationSnapshot)\n\t\t\tobjlist = append(objlist, eobj)\n\t\tdefault:\n\t\t\tlog.Fatalf(\"Got invalid object type %v while looking for ConfigurationSnapshot\", tp)\n\t\t}\n\t}\n\n\treturn objlist, nil\n}", "func List() {\n\tvar name string\n\tisGroup := false\n\n\tfmt.Printf(\"\\nShowing %v conversation(s):\\n\", len(jsonData))\n\n\t//jsonDataList := *jsonDatap\n\n\tfor i, block := range jsonData {\n\n\t\tfor _, participant := range block.Participants {\n\t\t\tif participant == master {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(block.Participants) >= 3 {\n\t\t\t\tisGroup = true\n\t\t\t}\n\t\t\tname = participant\n\t\t}\n\t\tif !isGroup {\n\t\t\tfmt.Printf(\"[%v] - %v\\n\", i, name)\n\t\t} else {\n\t\t\tfmt.Printf(\"[%v] - group: participants %+v\\n\", i, block.Participants)\n\t\t\tisGroup = false\n\t\t}\n\t}\n\n\tfmt.Println(\"\")\n}", "func (ccv *CCV) List(label string) []Section {\n\treturn ccv.Sections\n}", "func (c *Client) ListAll(ctx context.Context, p *ListAllPayload) (res *PageOfStations, err error) {\n\tvar ires interface{}\n\tires, err = c.ListAllEndpoint(ctx, p)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn ires.(*PageOfStations), nil\n}", "func (s sMBNamespaceLister) List(selector labels.Selector) (ret []*v1.SMB, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.SMB))\n\t})\n\treturn ret, err\n}", "func (r *Repository) List(filter models.RightFilter, limit, offset uint) (rights []models.FutureEndorsementRight, err error) {\n\tdb := r.getDb(filter)\n\terr = db.Order(\"block_level asc\").\n\t\tOffset(offset).\n\t\tLimit(limit).\n\t\tFind(&rights).Error\n\n\treturn rights, err\n}", "func (l *Location) List() ([]string, error) {\n\n\tvar filenames []string\n\tclient, err := l.fileSystem.Client(l.Authority)\n\tif err != nil {\n\t\treturn filenames, err\n\t}\n\t// start timer once action is completed\n\tdefer l.fileSystem.connTimerStart()\n\n\tfileinfos, err := client.ReadDir(l.Path())\n\tif err != nil {\n\t\tif err == os.ErrNotExist {\n\t\t\treturn filenames, nil\n\t\t}\n\t\treturn filenames, err\n\t}\n\tfor _, fileinfo := range fileinfos {\n\t\tif !fileinfo.IsDir() {\n\t\t\tfilenames = append(filenames, fileinfo.Name())\n\t\t}\n\t}\n\n\treturn filenames, nil\n}", "func (h *Handler) ListAll() ([]*corev1.Node, error) {\n\treturn h.ListByLabel(\"\")\n}", "func (s *sMBLister) List(selector labels.Selector) (ret []*v1.SMB, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.SMB))\n\t})\n\treturn ret, err\n}", "func (s *LocationsService) List(ctx context.Context) ([]Location, *Response, error) {\n\tpath := fmt.Sprintf(\"%v/\", locationsBasePath)\n\n\treq, err := s.client.NewRequest(http.MethodGet, path, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\troot := new(locationsRoot)\n\tresp, err := s.client.Do(ctx, req, root)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\tif m := root.Meta; m != nil {\n\t\tresp.Meta = m\n\t}\n\n\treturn root.Locations, resp, nil\n}", "func (a *IqnpoolApiService) GetIqnpoolBlockList(ctx context.Context) ApiGetIqnpoolBlockListRequest {\n\treturn ApiGetIqnpoolBlockListRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (c *Client) ListSnapshotRollOwners(ctx context.Context, id BlockID, cycle, index int64) (*SnapshotOwners, error) {\n\towners := &SnapshotOwners{Cycle: cycle, Index: index}\n\tu := fmt.Sprintf(\"chains/main/blocks/%s/context/raw/json/rolls/owner/snapshot/%d/%d?depth=1\", id, cycle, index)\n\tif err := c.Get(ctx, u, &owners.Rolls); err != nil {\n\t\treturn nil, err\n\t}\n\treturn owners, nil\n}", "func (c *MultiClusterController) List(clusterName string, opts ...client.ListOption) (interface{}, error) {\n\tcluster := c.GetCluster(clusterName)\n\tif cluster == nil {\n\t\treturn nil, errors.NewClusterNotFound(clusterName)\n\t}\n\tinstanceList := utilscheme.Scheme.NewObjectList(c.objectType)\n\tdelegatingClient, err := cluster.GetDelegatingClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = delegatingClient.List(context.TODO(), instanceList, opts...)\n\treturn instanceList, err\n}", "func (s *monitorMetricAlertruleLister) List(selector labels.Selector) (ret []*v1alpha1.MonitorMetricAlertrule, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.MonitorMetricAlertrule))\n\t})\n\treturn ret, err\n}", "func (s awsApiGatewayBasePathMappingNamespaceLister) List(selector labels.Selector) (ret []*v1.AwsApiGatewayBasePathMapping, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.AwsApiGatewayBasePathMapping))\n\t})\n\treturn ret, err\n}", "func (c *Client) List() ([]string, error) {\n\t// delegate to concrete implementation of lister entirely.\n\treturn c.lister.List()\n}", "func (_PlasmaFramework *PlasmaFrameworkCallerSession) Blocks(arg0 *big.Int) (struct {\n\tRoot [32]byte\n\tTimestamp *big.Int\n}, error) {\n\treturn _PlasmaFramework.Contract.Blocks(&_PlasmaFramework.CallOpts, arg0)\n}", "func (n *namespaceClient) List() ([]ns.Metadata, error) {\n\turl := fmt.Sprintf(\"%s%s\", n.url, nsh.GetURL)\n\tresp, err := n.client.DoHTTPRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdata := &admin.NamespaceGetResponse{}\n\tdefer func() {\n\t\tioutil.ReadAll(resp.Body)\n\t\tresp.Body.Close()\n\t}()\n\tif err := jsonpb.Unmarshal(resp.Body, data); err != nil {\n\t\treturn nil, err\n\t}\n\tnsMetas := []ns.Metadata{}\n\tfor nsID, nsOpts := range data.GetRegistry().GetNamespaces() {\n\t\tmd, err := ns.ToMetadata(nsID, nsOpts)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tnsMetas = append(nsMetas, md)\n\t}\n\tn.logger.Info(\"namespace retrieved\")\n\treturn nsMetas, nil\n}", "func (s *kylinNodeLister) List(selector labels.Selector) (ret []*v1.KylinNode, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.KylinNode))\n\t})\n\treturn ret, err\n}", "func (client *Client) List(path string) ([]*api.LsLink, error) {\n\treturn client.client.List(path)\n}", "func (v *VaultAccessor) List() (PathList, error) {\n\treturn v.list(v.basePath)\n}", "func (c *SubresourceClient) List(namespace string, labels map[string]string) (result []metav1.Object, e error) {\n\tif c.Error != \"\" {\n\t\te = fmt.Errorf(c.Error)\n\t} else {\n\t\tresult = []metav1.Object{c.Subresource}\n\t}\n\treturn\n}", "func (h HTTPHandler) CollectionList(w http.ResponseWriter, r *http.Request) {\n\terr := processJWT(r, false, h.secret)\n\tif err != nil {\n\t\thttp.Error(w, \"{\\\"message\\\": \\\"\"+err.Error()+\"\\\"}\", 401)\n\t\treturn\n\t}\n\n\tvar indexNames []string\n\tfor name := range h.bf.Local.Search.BlockchainIndices {\n\t\tindexNames = append(indexNames, name)\n\t}\n\n\trv := struct {\n\t\tMessage string `json:\"message\"`\n\t\tIndexes []string `json:\"collections\"`\n\t}{\n\t\tMessage: \"ok\",\n\t\tIndexes: indexNames,\n\t}\n\n\tmustEncode(w, rv)\n}", "func (_Bfs *BfsCallerSession) List(absolutePath string, offset *big.Int, limit *big.Int) (*big.Int, []BfsInfo, error) {\n\treturn _Bfs.Contract.List(&_Bfs.CallOpts, absolutePath, offset, limit)\n}", "func (core *coreService) RawBlocks(startHeight uint64, count uint64, withReceipts bool, withTransactionLogs bool) ([]*iotexapi.BlockInfo, error) {\n\tif count == 0 || count > core.cfg.RangeQueryLimit {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"range exceeds the limit\")\n\t}\n\n\ttipHeight := core.bc.TipHeight()\n\tif startHeight > tipHeight {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"start height should not exceed tip height\")\n\t}\n\tendHeight := startHeight + count - 1\n\tif endHeight > tipHeight {\n\t\tendHeight = tipHeight\n\t}\n\tvar res []*iotexapi.BlockInfo\n\tfor height := startHeight; height <= endHeight; height++ {\n\t\tblk, err := core.dao.GetBlockByHeight(height)\n\t\tif err != nil {\n\t\t\treturn nil, status.Error(codes.NotFound, err.Error())\n\t\t}\n\t\tvar receiptsPb []*iotextypes.Receipt\n\t\tif withReceipts && height > 0 {\n\t\t\treceipts, err := core.dao.GetReceipts(height)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, status.Error(codes.NotFound, err.Error())\n\t\t\t}\n\t\t\tfor _, receipt := range receipts {\n\t\t\t\treceiptsPb = append(receiptsPb, receipt.ConvertToReceiptPb())\n\t\t\t}\n\t\t}\n\t\tvar transactionLogs *iotextypes.TransactionLogs\n\t\tif withTransactionLogs {\n\t\t\tif transactionLogs, err = core.dao.TransactionLogs(height); err != nil {\n\t\t\t\treturn nil, status.Error(codes.NotFound, err.Error())\n\t\t\t}\n\t\t}\n\t\tres = append(res, &iotexapi.BlockInfo{\n\t\t\tBlock: blk.ConvertToBlockPb(),\n\t\t\tReceipts: receiptsPb,\n\t\t\tTransactionLogs: transactionLogs,\n\t\t})\n\t}\n\treturn res, nil\n}", "func (w *WebhookServiceOp) List(options interface{}) ([]Webhook, error) {\n\tpath := fmt.Sprintf(\"%s\", webhooksBasePath)\n\tresource := make([]Webhook, 0)\n\terr := w.client.Get(path, &resource, options)\n\treturn resource, err\n}", "func (c *MockNatGatewaysClient) List(ctx context.Context, resourceGroupName string) ([]network.NatGateway, error) {\n\tvar l []network.NatGateway\n\tfor _, ngw := range c.NGWs {\n\t\tl = append(l, ngw)\n\t}\n\treturn l, nil\n}", "func (r *MonitorNoneResource) ListAll() (*MonitorNoneList, error) {\n\tvar list MonitorNoneList\n\tif err := r.c.ReadQuery(BasePath+MonitorNoneEndpoint, &list); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &list, nil\n}", "func (lbq *LatestBlockQuery) All(ctx context.Context) ([]*LatestBlock, error) {\n\tif err := lbq.prepareQuery(ctx); err != nil {\n\t\treturn nil, err\n\t}\n\treturn lbq.sqlAll(ctx)\n}", "func (s wafregionalRuleNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.WafregionalRule, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.WafregionalRule))\n\t})\n\treturn ret, err\n}", "func (h *Handler) ListAll() ([]*unstructured.Unstructured, error) {\n\tlistOptions := h.Options.ListOptions.DeepCopy()\n\tlistOptions.LabelSelector = \"\"\n\n\tif err := h.getGVRAndNamespaceScope(); err != nil {\n\t\treturn nil, err\n\t}\n\tif h.isNamespaced {\n\t\treturn extractList(h.dynamicClient.Resource(h.gvr).Namespace(metav1.NamespaceAll).List(h.ctx, *listOptions))\n\t}\n\treturn extractList(h.dynamicClient.Resource(h.gvr).List(h.ctx, *listOptions))\n}", "func (c *Client) ListSnapshotBlocks(ctx context.Context, params *ListSnapshotBlocksInput, optFns ...func(*Options)) (*ListSnapshotBlocksOutput, error) {\n\tif params == nil {\n\t\tparams = &ListSnapshotBlocksInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"ListSnapshotBlocks\", params, optFns, addOperationListSnapshotBlocksMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*ListSnapshotBlocksOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func (s *kubeletConfigLister) List(selector labels.Selector) (ret []*v1.KubeletConfig, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.KubeletConfig))\n\t})\n\treturn ret, err\n}", "func (p *Proxy) List(w http.ResponseWriter, r *http.Request) {\n\tctx := r.Context()\n\tlogger := mPkg.GetLogger(ctx)\n\n\topt, err := fromHTTPRequestToListOptions(r, p.maxListLimit)\n\tif err != nil {\n\t\tlogger.Error(\"could not parse filter\", zap.Error(err))\n\t\trender.Render(w, r, cHttp.ErrResponse(http.StatusBadRequest, err.Error()))\n\n\t\treturn\n\t}\n\n\tlogger.Debug(\"Retrieving info for load tests\")\n\n\tloadTests, err := p.kubeClient.ListLoadTest(ctx, *opt)\n\tif err != nil {\n\t\tlogger.Error(\"could not list load tests\", zap.Error(err))\n\t\trender.Render(w, r, cHttp.ErrResponse(http.StatusInternalServerError, err.Error()))\n\n\t\treturn\n\t}\n\n\titems := make([]LoadTestStatus, len(loadTests.Items))\n\tfor i, lt := range loadTests.Items {\n\t\titems[i] = LoadTestStatus{\n\t\t\tType: lt.Spec.Type.String(),\n\t\t\tDistributedPods: *lt.Spec.DistributedPods,\n\t\t\tNamespace: lt.Status.Namespace,\n\t\t\tPhase: lt.Status.Phase.String(),\n\t\t\tTags: lt.Spec.Tags,\n\t\t\tHasEnvVars: len(lt.Spec.EnvVars) != 0,\n\t\t\tHasTestData: len(lt.Spec.TestData) != 0,\n\t\t}\n\t}\n\n\trender.JSON(w, r, &LoadTestStatusPage{\n\t\tLimit: opt.Limit,\n\t\tContinue: loadTests.Continue,\n\t\tRemain: loadTests.RemainingItemCount,\n\t\tItems: items,\n\t})\n}", "func (s *sensuAssetLister) List(selector labels.Selector) (ret []*v1beta1.SensuAsset, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.SensuAsset))\n\t})\n\treturn ret, err\n}", "func (s *scyllaDBMonitoringLister) List(selector labels.Selector) (ret []*v1alpha1.ScyllaDBMonitoring, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.ScyllaDBMonitoring))\n\t})\n\treturn ret, err\n}", "func (a *app) List(w http.ResponseWriter, request provider.Request, message rendererModel.Message) {\n\tfiles, err := a.storage.List(request.GetFilepath(\"\"))\n\tif err != nil {\n\t\ta.renderer.Error(w, request, provider.NewError(http.StatusInternalServerError, err))\n\t\treturn\n\t}\n\n\turi := request.GetURI(\"\")\n\n\titems := make([]provider.RenderItem, len(files))\n\tfor index, file := range files {\n\t\titems[index] = provider.RenderItem{\n\t\t\tID: sha.Sha1(file.Name),\n\t\t\tURI: uri,\n\t\t\tStorageItem: file,\n\t\t}\n\t}\n\n\tcontent := map[string]interface{}{\n\t\t\"Paths\": getPathParts(uri),\n\t\t\"Files\": items,\n\t\t\"Cover\": a.getCover(files),\n\t}\n\n\tif request.CanShare {\n\t\tcontent[\"Shares\"] = a.metadatas\n\t}\n\n\ta.renderer.Directory(w, request, content, message)\n}", "func (w *ClusterDynamicClient) List(opts metav1.ListOptions) (*unstructured.UnstructuredList, error) {\n\treturn w.dClient.Resource(w.resource).Namespace(w.namespace).List(w.ctx, opts)\n}", "func (obs *Observer) List(opts metav1.ListOptions) (*unstructured.UnstructuredList, error) {\n\treturn obs.client.Namespace(obs.namespace).List(opts)\n}", "func (ctl Controller) List() (*Info, *pitr.Error) {\n\tstdout, stderr, err := ctl.runner.Run(\"sudo --login --user postgres wal-g backup-list\")\n\n\tif err != nil {\n\t\treturn nil, &pitr.Error{\n\t\t\tMessage: err.Error(),\n\t\t\tStdout: stdout,\n\t\t\tStderr: stderr,\n\t\t}\n\t}\n\n\tinfos, err := ParseListOutput(stdout)\n\n\tif err != nil {\n\t\treturn nil, &pitr.Error{\n\t\t\tMessage: \"Parse error\",\n\t\t\tStdout: stderr,\n\t\t\tStderr: stderr,\n\t\t}\n\t}\n\n\treturn infos, nil\n}", "func (c *Client) List(ctx context.Context) (res StoredBottleCollection, err error) {\n\tvar ires any\n\tires, err = c.ListEndpoint(ctx, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn ires.(StoredBottleCollection), nil\n}", "func (c *Client) List() goa.Endpoint {\n\treturn func(ctx context.Context, v interface{}) (interface{}, error) {\n\t\tinv := goagrpc.NewInvoker(\n\t\t\tBuildListFunc(c.grpccli, c.opts...),\n\t\t\tEncodeListRequest,\n\t\t\tDecodeListResponse)\n\t\tres, err := inv.Invoke(ctx, v)\n\t\tif err != nil {\n\t\t\treturn nil, goa.Fault(err.Error())\n\t\t}\n\t\treturn res, nil\n\t}\n}", "func (*OktetoClusterHelper) List() (map[string]string, error) {\n\treturn nil, ErrNotImplemented\n}", "func (h *kubeClient) List(ctx context.Context, list client.ObjectList, opts ...client.ListOption) error {\n\treturn h.client.List(ctx, list, opts...)\n}", "func (s *tridentOrchestratorLister) List(selector labels.Selector) (ret []*v1.TridentOrchestrator, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.TridentOrchestrator))\n\t})\n\treturn ret, err\n}", "func (client *Client) LoadIndexersList() error {\n var result Indexers\n response, err := client.sendGetRequest(&result, \"indexers\", \"\", nil, nil)\n if err != nil {\n return errors.JackettUnableToLoadIndexers.ToError(err)\n }\n client.indexers = response.(*Indexers)\n configuredIndexers := make([]Indexer, 0)\n for _, indexer := range result {\n if indexer.Configured {\n configuredIndexers = append(configuredIndexers, indexer)\n }\n }\n client.configuredIndexers = configuredIndexers\n return nil\n}", "func (s scyllaDBMonitoringNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.ScyllaDBMonitoring, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.ScyllaDBMonitoring))\n\t})\n\treturn ret, err\n}", "func (r *FailoverResource) ListAll() (*FailoverConfigList, error) {\n\tvar list FailoverConfigList\n\tif err := r.c.ReadQuery(BasePath+FailoverEndpoint, &list); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &list, nil\n}", "func (c *aITrainingJobs) List(opts metav1.ListOptions) (result *v1.AITrainingJobList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = &v1.AITrainingJobList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"aitrainingjobs\").\n\t\tVersionedParams(&opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo().\n\t\tInto(result)\n\treturn\n}", "func (k *kubeclient) List(opts metav1.ListOptions) (*apis.CStorVolumeReplicaList, error) {\n\tcli, err := k.getClientOrCached()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn k.list(cli, k.namespace, opts)\n}", "func (s monitorMetricAlertruleNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.MonitorMetricAlertrule, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.MonitorMetricAlertrule))\n\t})\n\treturn ret, err\n}", "func (c *TestProjectConfig) GetRolloutList() (rolloutList []entities.Rollout) {\n\tfor _, rollout := range c.RolloutMap {\n\t\trolloutList = append(rolloutList, rollout)\n\t}\n\treturn rolloutList\n}", "func (c *clbClient) Lbs() []string {\n\treturn c.loadBalancers\n}", "func (i *instrumentedListerWatcher) List(options metav1.ListOptions) (runtime.Object, error) {\n\ti.listTotal.Inc()\n\tret, err := i.next.List(options)\n\tif err != nil {\n\t\ti.listFailed.Inc()\n\t}\n\treturn ret, err\n}", "func (c *ConsulClient) List(ctx context.Context, prefix string) ([]Pair, error) {\n\tspan, ctx := opentracing.StartSpanFromContext(ctx, \"ConsulClient.List\")\n\tdefer span.Finish()\n\n\tregistryOperationCount.WithLabelValues(env, \"List\").Inc()\n\n\tstartTime := time.Now()\n\tdefer func() {\n\t\tregistryOperationTimeTaken.WithLabelValues(env, \"List\").Observe(time.Now().Sub(startTime).Seconds())\n\t}()\n\n\tkvs, _, err := c.client.KV().List(prefix, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpairs := []Pair{}\n\n\tfor _, kv := range kvs {\n\t\tpairs = append(pairs, Pair{\n\t\t\tKey: kv.Key,\n\t\t\tValue: kv.Value,\n\t\t})\n\t}\n\n\treturn pairs, nil\n}", "func (t table) List() []string {\n\treturn t.ls[:]\n}", "func List(ctx context.Context, filters container.FilterBuilder) ([]*types.Node, error) {\n\tres := []*types.Node{}\n\tvisit := func(ctx context.Context, cluster string, node *types.Node) {\n\t\tres = append(res, node)\n\t}\n\treturn res, list(ctx, visit, filters)\n}", "func (s sealedSecretNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.SealedSecret, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.SealedSecret))\n\t})\n\treturn ret, err\n}", "func (w *Wallet) ListSinceBlock(start, end, syncHeight int32) ([]btcjson.ListTransactionsResult, er.R) {\n\ttxList := []btcjson.ListTransactionsResult{}\n\terr := walletdb.View(w.db, func(tx walletdb.ReadTx) er.R {\n\t\ttxmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)\n\n\t\trangeFn := func(details []wtxmgr.TxDetails) (bool, er.R) {\n\t\t\tfor _, detail := range details {\n\t\t\t\tjsonResults := listTransactions(tx, &detail,\n\t\t\t\t\tw.Manager, syncHeight, w.chainParams)\n\t\t\t\ttxList = append(txList, jsonResults...)\n\t\t\t}\n\t\t\treturn false, nil\n\t\t}\n\n\t\treturn w.TxStore.RangeTransactions(txmgrNs, start, end, rangeFn)\n\t})\n\treturn txList, err\n}", "func (s *logicalNetworkLister) List(selector labels.Selector) (ret []*v1.LogicalNetwork, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.LogicalNetwork))\n\t})\n\treturn ret, err\n}", "func (s *seaOtterLister) List(selector labels.Selector) (ret []*v1alpha1.SeaOtter, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.SeaOtter))\n\t})\n\treturn ret, err\n}", "func (c *clientBackup) List(ctx context.Context, opt *BackupListOptions) (map[BackupID]BackupMeta, error) {\n\treq, err := c.conn.NewRequest(\"POST\", \"_admin/backup/list\")\n\tif err != nil {\n\t\treturn nil, WithStack(err)\n\t}\n\tapplyContextSettings(ctx, req)\n\tif opt != nil {\n\t\treq, err = req.SetBody(opt)\n\t\tif err != nil {\n\t\t\treturn nil, WithStack(err)\n\t\t}\n\t}\n\tresp, err := c.conn.Do(ctx, req)\n\tif err != nil {\n\t\treturn nil, WithStack(err)\n\t}\n\tif err := resp.CheckStatus(200); err != nil {\n\t\treturn nil, WithStack(err)\n\t}\n\tvar result struct {\n\t\tList map[BackupID]BackupMeta `json:\"list,omitempty\"`\n\t}\n\tif err := resp.ParseBody(\"result\", &result); err != nil {\n\t\treturn nil, WithStack(err)\n\t}\n\treturn result.List, nil\n}" ]
[ "0.7311063", "0.6322645", "0.60686725", "0.60537857", "0.58911", "0.552953", "0.5229831", "0.5191888", "0.51698", "0.51621276", "0.515386", "0.5137676", "0.5080767", "0.50736266", "0.5053302", "0.50126654", "0.4932627", "0.4914542", "0.4912257", "0.49045357", "0.49037486", "0.48964658", "0.4876176", "0.4875737", "0.4869453", "0.48463058", "0.48193884", "0.48145556", "0.48071375", "0.47808182", "0.47755313", "0.47655818", "0.47638363", "0.4755005", "0.47451144", "0.4743474", "0.47424784", "0.47391406", "0.47310314", "0.47306013", "0.47114918", "0.4705923", "0.4705104", "0.46999678", "0.46901548", "0.46881026", "0.46867", "0.46865544", "0.4684137", "0.4672462", "0.46717027", "0.46690086", "0.46675965", "0.46629792", "0.46573225", "0.4652886", "0.46419895", "0.4640344", "0.46390072", "0.46335837", "0.46313947", "0.46270344", "0.46199128", "0.46174735", "0.46169078", "0.46115476", "0.46080488", "0.459587", "0.45939606", "0.45886648", "0.45861307", "0.4585727", "0.45797417", "0.45772183", "0.45660332", "0.45622367", "0.4561131", "0.4559264", "0.45589057", "0.45572695", "0.45480615", "0.45460266", "0.4545805", "0.45427328", "0.45330673", "0.45318377", "0.45317084", "0.45297956", "0.45274433", "0.4522804", "0.452194", "0.45135522", "0.4502472", "0.44908348", "0.44840217", "0.44813263", "0.44808108", "0.44778928", "0.44770664", "0.44762596" ]
0.76020056
0
RolloutBlocks returns an object that can list and get RolloutBlocks.
RolloutBlocks возвращает объект, который может перечислять и получать RolloutBlocks.
func (s *rolloutBlockLister) RolloutBlocks(namespace string) RolloutBlockNamespaceLister { return rolloutBlockNamespaceLister{indexer: s.indexer, namespace: namespace} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewRolloutBlockLister(indexer cache.Indexer) RolloutBlockLister {\n\treturn &rolloutBlockLister{indexer: indexer}\n}", "func (l *LessonTut) Blocks() []*BlockTut { return l.blocks }", "func (s rolloutBlockNamespaceLister) Get(name string) (*v1alpha1.RolloutBlock, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"rolloutblock\"), name)\n\t}\n\treturn obj.(*v1alpha1.RolloutBlock), nil\n}", "func (s *rolloutBlockLister) List(selector labels.Selector) (ret []*v1alpha1.RolloutBlock, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.RolloutBlock))\n\t})\n\treturn ret, err\n}", "func Block(b models.Block) *genModels.BlocksRow {\n\tts := b.Timestamp.Unix()\n\n\tgenBlock := genModels.BlocksRow{\n\t\tLevel: b.Level.Ptr(),\n\t\tProto: b.Proto.Ptr(),\n\t\tBlockTime: b.BlockTime,\n\t\tPredecessor: b.Predecessor.Ptr(),\n\t\tTimestamp: &ts,\n\t\tValidationPass: b.ValidationPass.Ptr(),\n\t\tFitness: b.Fitness.Ptr(),\n\t\tContext: b.Context,\n\t\tSignature: b.Signature,\n\t\tProtocol: b.Protocol.Ptr(),\n\t\tPriority: b.Priority.Ptr(),\n\t\tChainID: b.ChainID,\n\t\tHash: b.Hash.Ptr(),\n\t\tReward: &b.Reward,\n\t\tDeposit: b.Deposit,\n\t\tOperationsHash: b.OperationsHash,\n\t\tPeriodKind: b.PeriodKind,\n\t\tCurrentExpectedQuorum: b.CurrentExpectedQuorum,\n\t\tActiveProposal: b.ActiveProposal,\n\t\tBaker: b.Baker,\n\t\tBakerName: b.BakerName,\n\t\tNonceHash: b.NonceHash,\n\t\tConsumedGas: b.ConsumedGas,\n\t\tMetaLevel: b.MetaLevel,\n\t\tMetaLevelPosition: b.MetaLevelPosition,\n\t\tMetaCycle: b.MetaCycle,\n\t\tMetaCyclePosition: b.MetaCyclePosition,\n\t\tMetaVotingPeriod: b.MetaVotingPeriod,\n\t\tMetaVotingPeriodPosition: b.MetaVotingPeriodPosition,\n\t\tExpectedCommitment: b.ExpectedCommitment,\n\t}\n\n\tif b.BlockAggregation != nil {\n\t\tgenBlock.Volume = b.BlockAggregation.Volume\n\t\tgenBlock.Fees = b.BlockAggregation.Fees\n\t\tgenBlock.Endorsements = b.BlockAggregation.Endorsements\n\t\tgenBlock.Proposals = b.BlockAggregation.Proposals\n\t\tgenBlock.SeedNonceRevelations = b.BlockAggregation.SeedNonceRevelations\n\t\tgenBlock.Delegations = b.BlockAggregation.Delegations\n\t\tgenBlock.Transactions = b.BlockAggregation.Transactions\n\t\tgenBlock.ActivateAccounts = b.BlockAggregation.ActivateAccounts\n\t\tgenBlock.Ballots = b.BlockAggregation.Ballots\n\t\tgenBlock.Originations = b.BlockAggregation.Originations\n\t\tgenBlock.Reveals = b.BlockAggregation.Reveals\n\t\tgenBlock.DoubleBakingEvidence = b.BlockAggregation.DoubleBakingEvidences\n\t\tgenBlock.DoubleEndorsementEvidence = b.BlockAggregation.DoubleEndorsementEvidences\n\t\tgenBlock.NumberOfOperations = b.BlockAggregation.NumberOfOperations\n\t}\n\n\treturn &genBlock\n}", "func (s rolloutBlockNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.RolloutBlock, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.RolloutBlock))\n\t})\n\treturn ret, err\n}", "func Blocks(offset, count uint) ([]BlockItem, error) {\n\tjsonBlocks := []struct {\n\t\tNumber uint `json:\"number\"`\n\t\tHash string `json:\"hash\"`\n\t\tDate Time `json:\"date\"`\n\t\tDifficulty uint64 `json:\"difficulty\"`\n\t\tMiner string `json:\"miner\"`\n\t}{}\n\tif err := fetch(&jsonBlocks, blockEndpoint, offset, count); err != nil {\n\t\treturn nil, err\n\t}\n\tblocks := make([]BlockItem, len(jsonBlocks))\n\tfor i, b := range jsonBlocks {\n\t\tblocks[i] = BlockItem(b)\n\t}\n\treturn blocks, nil\n}", "func (core *coreService) RawBlocks(startHeight uint64, count uint64, withReceipts bool, withTransactionLogs bool) ([]*iotexapi.BlockInfo, error) {\n\tif count == 0 || count > core.cfg.RangeQueryLimit {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"range exceeds the limit\")\n\t}\n\n\ttipHeight := core.bc.TipHeight()\n\tif startHeight > tipHeight {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"start height should not exceed tip height\")\n\t}\n\tendHeight := startHeight + count - 1\n\tif endHeight > tipHeight {\n\t\tendHeight = tipHeight\n\t}\n\tvar res []*iotexapi.BlockInfo\n\tfor height := startHeight; height <= endHeight; height++ {\n\t\tblk, err := core.dao.GetBlockByHeight(height)\n\t\tif err != nil {\n\t\t\treturn nil, status.Error(codes.NotFound, err.Error())\n\t\t}\n\t\tvar receiptsPb []*iotextypes.Receipt\n\t\tif withReceipts && height > 0 {\n\t\t\treceipts, err := core.dao.GetReceipts(height)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, status.Error(codes.NotFound, err.Error())\n\t\t\t}\n\t\t\tfor _, receipt := range receipts {\n\t\t\t\treceiptsPb = append(receiptsPb, receipt.ConvertToReceiptPb())\n\t\t\t}\n\t\t}\n\t\tvar transactionLogs *iotextypes.TransactionLogs\n\t\tif withTransactionLogs {\n\t\t\tif transactionLogs, err = core.dao.TransactionLogs(height); err != nil {\n\t\t\t\treturn nil, status.Error(codes.NotFound, err.Error())\n\t\t\t}\n\t\t}\n\t\tres = append(res, &iotexapi.BlockInfo{\n\t\t\tBlock: blk.ConvertToBlockPb(),\n\t\t\tReceipts: receiptsPb,\n\t\t\tTransactionLogs: transactionLogs,\n\t\t})\n\t}\n\treturn res, nil\n}", "func (_PlasmaFramework *PlasmaFrameworkCaller) Blocks(opts *bind.CallOpts, arg0 *big.Int) (struct {\n\tRoot [32]byte\n\tTimestamp *big.Int\n}, error) {\n\tret := new(struct {\n\t\tRoot [32]byte\n\t\tTimestamp *big.Int\n\t})\n\tout := ret\n\terr := _PlasmaFramework.contract.Call(opts, out, \"blocks\", arg0)\n\treturn *ret, err\n}", "func (_PlasmaFramework *PlasmaFrameworkSession) Blocks(arg0 *big.Int) (struct {\n\tRoot [32]byte\n\tTimestamp *big.Int\n}, error) {\n\treturn _PlasmaFramework.Contract.Blocks(&_PlasmaFramework.CallOpts, arg0)\n}", "func (b *Block) List(input *BlockCursorInput) (*Blocks, error) {\n\tparams := make(map[string]string)\n\tparams[\"cursor\"] = input.Cursor\n\tresp, err := b.c.Request(http.MethodGet, \"/blocks\", new(bytes.Buffer), params)\n\tif err != nil {\n\t\treturn &Blocks{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar blocks *Blocks\n\terr = json.NewDecoder(resp.Body).Decode(&blocks)\n\tif err != nil {\n\t\treturn &Blocks{}, err\n\t}\n\treturn blocks, nil\n}", "func (_PlasmaFramework *PlasmaFrameworkCallerSession) Blocks(arg0 *big.Int) (struct {\n\tRoot [32]byte\n\tTimestamp *big.Int\n}, error) {\n\treturn _PlasmaFramework.Contract.Blocks(&_PlasmaFramework.CallOpts, arg0)\n}", "func Blocks(bs []models.Block) []*genModels.BlocksRow {\n\tblocks := make([]*genModels.BlocksRow, len(bs))\n\tfor i := range bs {\n\t\tblocks[i] = Block(bs[i])\n\t}\n\treturn blocks\n}", "func (nc *NSBClient) GetBlocks(rangeL, rangeR int64) (*BlocksInfo, error) {\n\tb, err := nc.handler.Group(\"/blockchain\").GetWithParams(request.Param{\n\t\t\"minHeight\": rangeL,\n\t\t\"maxHeight\": rangeR,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar bb []byte\n\tbb, err = nc.preloadJSONResponse(b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar a BlocksInfo\n\terr = json.Unmarshal(bb, &a)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &a, nil\n}", "func (m *BlocksMessage) GetBlocks() ([]*types.Block, error) {\n\tblocks := []*types.Block{}\n\tfor _, data := range m.RawBlocks {\n\t\tblock := &types.Block{}\n\t\tif err := json.Unmarshal(data, block); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tblocks = append(blocks, block)\n\t}\n\treturn blocks, nil\n}", "func (s *Service) GetExplorerBlocks(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tfrom := r.FormValue(\"from\")\n\tto := r.FormValue(\"to\")\n\tpageParam := r.FormValue(\"page\")\n\toffsetParam := r.FormValue(\"offset\")\n\torder := r.FormValue(\"order\")\n\tdata := &Data{\n\t\tBlocks: []*Block{},\n\t}\n\tdefer func() {\n\t\tif err := json.NewEncoder(w).Encode(data.Blocks); err != nil {\n\t\t\tutils.Logger().Warn().Err(err).Msg(\"cannot JSON-encode blocks\")\n\t\t}\n\t}()\n\n\tif from == \"\" {\n\t\tutils.Logger().Warn().Msg(\"Missing from parameter\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\tdb := s.Storage.GetDB()\n\tfromInt, err := strconv.Atoi(from)\n\tif err != nil {\n\t\tutils.Logger().Warn().Err(err).Msg(\"invalid from parameter\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\tvar toInt int\n\tif to == \"\" {\n\t\ttoInt, err = func() (int, error) {\n\t\t\tbytes, err := db.Get([]byte(BlockHeightKey))\n\t\t\tif err == nil {\n\t\t\t\treturn strconv.Atoi(string(bytes))\n\t\t\t}\n\t\t\treturn toInt, err\n\t\t}()\n\t} else {\n\t\ttoInt, err = strconv.Atoi(to)\n\t}\n\tif err != nil {\n\t\tutils.Logger().Warn().Err(err).Msg(\"invalid to parameter\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\tvar offset int\n\tif offsetParam != \"\" {\n\t\toffset, err = strconv.Atoi(offsetParam)\n\t\tif err != nil || offset < 1 {\n\t\t\tutils.Logger().Warn().Msg(\"invalid offset parameter\")\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\toffset = paginationOffset\n\t}\n\tvar page int\n\tif pageParam != \"\" {\n\t\tpage, err = strconv.Atoi(pageParam)\n\t\tif err != nil {\n\t\t\tutils.Logger().Warn().Err(err).Msg(\"invalid page parameter\")\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tpage = 0\n\t}\n\n\taccountBlocks := s.ReadBlocksFromDB(fromInt, toInt)\n\tfor id, accountBlock := range accountBlocks {\n\t\tif id == 0 || id == len(accountBlocks)-1 || accountBlock == nil {\n\t\t\tcontinue\n\t\t}\n\t\tblock := NewBlock(accountBlock, id+fromInt-1)\n\t\t// Populate transactions\n\t\tfor _, tx := range accountBlock.Transactions() {\n\t\t\ttransaction := GetTransaction(tx, accountBlock)\n\t\t\tif transaction != nil {\n\t\t\t\tblock.TXs = append(block.TXs, transaction)\n\t\t\t}\n\t\t}\n\t\tif accountBlocks[id-1] == nil {\n\t\t\tblock.BlockTime = int64(0)\n\t\t\tblock.PrevBlock = RefBlock{\n\t\t\t\tID: \"\",\n\t\t\t\tHeight: \"\",\n\t\t\t}\n\t\t} else {\n\t\t\tblock.BlockTime = accountBlock.Time().Int64() - accountBlocks[id-1].Time().Int64()\n\t\t\tblock.PrevBlock = RefBlock{\n\t\t\t\tID: accountBlocks[id-1].Hash().Hex(),\n\t\t\t\tHeight: strconv.Itoa(id + fromInt - 2),\n\t\t\t}\n\t\t}\n\t\tif accountBlocks[id+1] == nil {\n\t\t\tblock.NextBlock = RefBlock{\n\t\t\t\tID: \"\",\n\t\t\t\tHeight: \"\",\n\t\t\t}\n\t\t} else {\n\t\t\tblock.NextBlock = RefBlock{\n\t\t\t\tID: accountBlocks[id+1].Hash().Hex(),\n\t\t\t\tHeight: strconv.Itoa(id + fromInt),\n\t\t\t}\n\t\t}\n\t\tdata.Blocks = append(data.Blocks, block)\n\t}\n\tif offset*page >= len(data.Blocks) {\n\t\tdata.Blocks = []*Block{}\n\t} else if offset*page+offset > len(data.Blocks) {\n\t\tdata.Blocks = data.Blocks[offset*page:]\n\t} else {\n\t\tdata.Blocks = data.Blocks[offset*page : offset*page+offset]\n\t}\n\tif order == \"DESC\" {\n\t\tsort.Slice(data.Blocks[:], func(i, j int) bool {\n\t\t\treturn data.Blocks[i].Timestamp > data.Blocks[j].Timestamp\n\t\t})\n\t} else {\n\t\tsort.Slice(data.Blocks[:], func(i, j int) bool {\n\t\t\treturn data.Blocks[i].Timestamp < data.Blocks[j].Timestamp\n\t\t})\n\t}\n}", "func (obj Events) Block() Block {\n\treturn Block(obj)\n}", "func (t *Thread) Blocks(offsetId string, limit int) []repo.Block {\n\tlog.Debugf(\"listing blocks: offsetId: %s, limit: %d, thread: %s\", offsetId, limit, t.Name)\n\tquery := fmt.Sprintf(\"pk='%s' and type=%d\", t.Id, repo.PhotoBlock)\n\tlist := t.blocks().List(offsetId, limit, query)\n\tlog.Debugf(\"found %d photos in thread %s\", len(list), t.Name)\n\treturn list\n}", "func (_Rootchain *RootchainCaller) Blocks(opts *bind.CallOpts, arg0 *big.Int) (struct {\n\tRoot [32]byte\n\tTimestamp *big.Int\n}, error) {\n\tret := new(struct {\n\t\tRoot [32]byte\n\t\tTimestamp *big.Int\n\t})\n\tout := ret\n\terr := _Rootchain.contract.Call(opts, out, \"blocks\", arg0)\n\treturn *ret, err\n}", "func consensusBlocksGetFromBlock(b types.Block, h types.BlockHeight) ConsensusBlocksGet {\n\ttxns := make([]ConsensusBlocksGetTxn, 0, len(b.Transactions))\n\tfor _, t := range b.Transactions {\n\t\t// Get the transaction's SiacoinOutputs.\n\t\tscos := make([]ConsensusBlocksGetSiacoinOutput, 0, len(t.SiacoinOutputs))\n\t\tfor i, sco := range t.SiacoinOutputs {\n\t\t\tscos = append(scos, ConsensusBlocksGetSiacoinOutput{\n\t\t\t\tID: t.SiacoinOutputID(uint64(i)),\n\t\t\t\tValue: sco.Value,\n\t\t\t\tUnlockHash: sco.UnlockHash,\n\t\t\t})\n\t\t}\n\t\t// Get the transaction's SiafundOutputs.\n\t\tsfos := make([]ConsensusBlocksGetSiafundOutput, 0, len(t.SiafundOutputs))\n\t\tfor i, sfo := range t.SiafundOutputs {\n\t\t\tsfos = append(sfos, ConsensusBlocksGetSiafundOutput{\n\t\t\t\tID: t.SiafundOutputID(uint64(i)),\n\t\t\t\tValue: sfo.Value,\n\t\t\t\tUnlockHash: sfo.UnlockHash,\n\t\t\t})\n\t\t}\n\t\t// Get the transaction's FileContracts.\n\t\tfcos := make([]ConsensusBlocksGetFileContract, 0, len(t.FileContracts))\n\t\tfor i, fc := range t.FileContracts {\n\t\t\t// Get the FileContract's valid proof outputs.\n\t\t\tfcid := t.FileContractID(uint64(i))\n\t\t\tvpos := make([]ConsensusBlocksGetSiacoinOutput, 0, len(fc.ValidProofOutputs))\n\t\t\tfor j, vpo := range fc.ValidProofOutputs {\n\t\t\t\tvpos = append(vpos, ConsensusBlocksGetSiacoinOutput{\n\t\t\t\t\tID: fcid.StorageProofOutputID(types.ProofValid, uint64(j)),\n\t\t\t\t\tValue: vpo.Value,\n\t\t\t\t\tUnlockHash: vpo.UnlockHash,\n\t\t\t\t})\n\t\t\t}\n\t\t\t// Get the FileContract's missed proof outputs.\n\t\t\tmpos := make([]ConsensusBlocksGetSiacoinOutput, 0, len(fc.MissedProofOutputs))\n\t\t\tfor j, mpo := range fc.MissedProofOutputs {\n\t\t\t\tmpos = append(mpos, ConsensusBlocksGetSiacoinOutput{\n\t\t\t\t\tID: fcid.StorageProofOutputID(types.ProofMissed, uint64(j)),\n\t\t\t\t\tValue: mpo.Value,\n\t\t\t\t\tUnlockHash: mpo.UnlockHash,\n\t\t\t\t})\n\t\t\t}\n\t\t\tfcos = append(fcos, ConsensusBlocksGetFileContract{\n\t\t\t\tID: fcid,\n\t\t\t\tFileSize: fc.FileSize,\n\t\t\t\tFileMerkleRoot: fc.FileMerkleRoot,\n\t\t\t\tWindowStart: fc.WindowStart,\n\t\t\t\tWindowEnd: fc.WindowEnd,\n\t\t\t\tPayout: fc.Payout,\n\t\t\t\tValidProofOutputs: vpos,\n\t\t\t\tMissedProofOutputs: mpos,\n\t\t\t\tUnlockHash: fc.UnlockHash,\n\t\t\t\tRevisionNumber: fc.RevisionNumber,\n\t\t\t})\n\t\t}\n\t\ttxns = append(txns, ConsensusBlocksGetTxn{\n\t\t\tID: t.ID(),\n\t\t\tSiacoinInputs: t.SiacoinInputs,\n\t\t\tSiacoinOutputs: scos,\n\t\t\tFileContracts: fcos,\n\t\t\tFileContractRevisions: t.FileContractRevisions,\n\t\t\tStorageProofs: t.StorageProofs,\n\t\t\tSiafundInputs: t.SiafundInputs,\n\t\t\tSiafundOutputs: sfos,\n\t\t\tMinerFees: t.MinerFees,\n\t\t\tArbitraryData: t.ArbitraryData,\n\t\t\tTransactionSignatures: t.TransactionSignatures,\n\t\t})\n\t}\n\treturn ConsensusBlocksGet{\n\t\tID: b.ID(),\n\t\tHeight: h,\n\t\tParentID: b.ParentID,\n\t\tNonce: b.Nonce,\n\t\tTimestamp: b.Timestamp,\n\t\tMinerPayouts: b.MinerPayouts,\n\t\tTransactions: txns,\n\t}\n}", "func (ts *Tipset) Block(miner Miner, winCount int64, msgs ...*ApplicableMessage) {\n\tblock := Block{\n\t\tMinerAddr: miner.MinerActorAddr.ID,\n\t\tWinCount: winCount,\n\t}\n\tfor _, am := range msgs {\n\t\tblock.Messages = append(block.Messages, MustSerialize(am.Message))\n\n\t\t// if we see this message for the first time, add it to the `msgIdx` map and to the `orderMsgs` slice.\n\t\tif _, ok := ts.tss.msgIdx[am.Message.Cid()]; !ok {\n\t\t\tts.tss.msgIdx[am.Message.Cid()] = am\n\t\t\tts.tss.orderedMsgs = append(ts.tss.orderedMsgs, am)\n\t\t}\n\t}\n\n\tts.Blocks = append(ts.Blocks, block)\n}", "func (_Rootchain *RootchainSession) Blocks(arg0 *big.Int) (struct {\n\tRoot [32]byte\n\tTimestamp *big.Int\n}, error) {\n\treturn _Rootchain.Contract.Blocks(&_Rootchain.CallOpts, arg0)\n}", "func (core *coreService) BlockByHeightRange(start uint64, count uint64) ([]*apitypes.BlockWithReceipts, error) {\n\tif count == 0 {\n\t\treturn nil, errors.Wrap(errInvalidFormat, \"count must be greater than zero\")\n\t}\n\tif count > core.cfg.RangeQueryLimit {\n\t\treturn nil, errors.Wrap(errInvalidFormat, \"range exceeds the limit\")\n\t}\n\n\tvar (\n\t\ttipHeight = core.bc.TipHeight()\n\t\tres = make([]*apitypes.BlockWithReceipts, 0)\n\t)\n\tif start > tipHeight {\n\t\treturn nil, errors.Wrap(errInvalidFormat, \"start height should not exceed tip height\")\n\t}\n\tfor height := start; height <= tipHeight && count > 0; height++ {\n\t\tblkStore, err := core.getBlockByHeight(height)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tres = append(res, blkStore)\n\t\tcount--\n\t}\n\treturn res, nil\n}", "func (c *Client) GetBlocks(height string) (resp *Blocks, e error) {\n\tif height == \"\" {\n\t\treturn nil, c.err(ErrBEW)\n\t}\n\n\tresp = &Blocks{}\n\treturn resp, c.Do(\"/blocks/\"+height, resp, nil)\n}", "func GetBlocks(hostURL string, hostPort int, height int) *bytes.Buffer {\n\tparams := make(map[string]interface{})\n\tparams[\"height\"] = height\n\treturn makePostRequest(hostURL, hostPort, \"f_blocks_list_json\", params)\n}", "func (_Rootchain *RootchainCallerSession) Blocks(arg0 *big.Int) (struct {\n\tRoot [32]byte\n\tTimestamp *big.Int\n}, error) {\n\treturn _Rootchain.Contract.Blocks(&_Rootchain.CallOpts, arg0)\n}", "func (lp *logPoller) GetBlocksRange(ctx context.Context, numbers []uint64, qopts ...pg.QOpt) ([]LogPollerBlock, error) {\n\tvar blocks []LogPollerBlock\n\n\t// Do nothing if no blocks are requested.\n\tif len(numbers) == 0 {\n\t\treturn blocks, nil\n\t}\n\n\t// Assign the requested blocks to a mapping.\n\tblocksRequested := make(map[uint64]struct{})\n\tfor _, b := range numbers {\n\t\tblocksRequested[b] = struct{}{}\n\t}\n\n\t// Retrieve all blocks within this range from the log poller.\n\tblocksFound := make(map[uint64]LogPollerBlock)\n\tqopts = append(qopts, pg.WithParentCtx(ctx))\n\tminRequestedBlock := mathutil.Min(numbers[0], numbers[1:]...)\n\tmaxRequestedBlock := mathutil.Max(numbers[0], numbers[1:]...)\n\tlpBlocks, err := lp.orm.GetBlocksRange(minRequestedBlock, maxRequestedBlock, qopts...)\n\tif err != nil {\n\t\tlp.lggr.Warnw(\"Error while retrieving blocks from log pollers blocks table. Falling back to RPC...\", \"requestedBlocks\", numbers, \"err\", err)\n\t} else {\n\t\tfor _, b := range lpBlocks {\n\t\t\tif _, ok := blocksRequested[uint64(b.BlockNumber)]; ok {\n\t\t\t\t// Only fill requested blocks.\n\t\t\t\tblocksFound[uint64(b.BlockNumber)] = b\n\t\t\t}\n\t\t}\n\t\tlp.lggr.Debugw(\"Got blocks from log poller\", \"blockNumbers\", maps.Keys(blocksFound))\n\t}\n\n\t// Fill any remaining blocks from the client.\n\tblocksFoundFromRPC, err := lp.fillRemainingBlocksFromRPC(ctx, numbers, blocksFound)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor num, b := range blocksFoundFromRPC {\n\t\tblocksFound[num] = b\n\t}\n\n\tvar blocksNotFound []uint64\n\tfor _, num := range numbers {\n\t\tb, ok := blocksFound[num]\n\t\tif !ok {\n\t\t\tblocksNotFound = append(blocksNotFound, num)\n\t\t}\n\t\tblocks = append(blocks, b)\n\t}\n\n\tif len(blocksNotFound) > 0 {\n\t\treturn nil, errors.Errorf(\"blocks were not found in db or RPC call: %v\", blocksNotFound)\n\t}\n\n\treturn blocks, nil\n}", "func BlockStats(offset, count uint) ([]BlockStatItem, error) {\n\tjsonStats := []struct {\n\t\tDate Time `json:\"date\"`\n\t\tDifficulty uint64 `json:\"difficulty\"`\n\t\tBlockTime float64 `json:\"block_time\"`\n\t}{}\n\tif err := fetch(&jsonStats, blockStatsEndpoint, offset, count); err != nil {\n\t\treturn nil, err\n\t}\n\tstats := make([]BlockStatItem, len(jsonStats))\n\tfor i, s := range jsonStats {\n\t\tstats[i] = BlockStatItem(s)\n\t}\n\treturn stats, nil\n}", "func (c *Client) GetBlocks(ctx context.Context, pg *Pagination) ([]*Account, error) {\n\tvar accounts []*Account\n\terr := c.doAPI(ctx, http.MethodGet, \"/api/v1/blocks\", nil, &accounts, pg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn accounts, nil\n}", "func (d *Dataset) Blocks() []*Block {\n\treturn d.blocks\n}", "func BlocksBakingRights(bs []models.Block) []*genModels.BakingRightsPerBlock {\n\tblocks := make([]*genModels.BakingRightsPerBlock, len(bs))\n\tfor i := range bs {\n\t\tblocks[i] = BlockBakingRights(bs[i])\n\t}\n\treturn blocks\n}", "func (c *Client) Block() *Block {\n\treturn &Block{c}\n}", "func (c *RpcClient) GetBlocks(ctx context.Context, startSlot uint64, endSlot uint64) (GetBlocksResponse, error) {\n\treturn c.processGetBlocks(c.Call(ctx, \"getBlocks\", startSlot, endSlot))\n}", "func (w *FilteredBlockWrapper) Block() *pb.FilteredBlock {\r\n\treturn w.block\r\n}", "func (p *PageListOrderedItemBlocks) GetBlocks() (value []PageBlockClass) {\n\tif p == nil {\n\t\treturn\n\t}\n\treturn p.Blocks\n}", "func BlockAll(ctx context.Context) schema.Block {\n\treturn Block(ctx, Opts{\n\t\tCreate: true,\n\t\tRead: true,\n\t\tUpdate: true,\n\t\tDelete: true,\n\t})\n}", "func GetBlocks(w http.ResponseWriter, r *http.Request) {\n\t// Send a copy of this node's blockchain\n\tw.WriteHeader(http.StatusOK)\n\tjson.NewEncoder(w).Encode(b.blockchain)\n}", "func (ck *CertKey) CertBlocks() []*pem.Block { return ck.certBlocks }", "func (c *Client) Block() <-chan *types.Block {\n\treturn c.blocks\n}", "func (c *RPCClient) FilterBlocks(\n\treq *FilterBlocksRequest) (*FilterBlocksResponse, er.R) {\n\n\tblockFilterer := NewBlockFilterer(c.chainParams, req)\n\n\t// Construct the watchlist using the addresses and outpoints contained\n\t// in the filter blocks request.\n\twatchList, err := buildFilterBlocksWatchList(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Iterate over the requested blocks, fetching the compact filter for\n\t// each one, and matching it against the watchlist generated above. If\n\t// the filter returns a positive match, the full block is then requested\n\t// and scanned for addresses using the block filterer.\n\tfor i, blk := range req.Blocks {\n\t\trawFilter, err := c.GetCFilter(&blk.Hash, wire.GCSFilterRegular)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Ensure the filter is large enough to be deserialized.\n\t\tif len(rawFilter.Data) < 4 {\n\t\t\tcontinue\n\t\t}\n\n\t\tfilter, err := gcs.FromNBytes(\n\t\t\tbuilder.DefaultP, builder.DefaultM, rawFilter.Data,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Skip any empty filters.\n\t\tif filter.N() == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tkey := builder.DeriveKey(&blk.Hash)\n\t\tmatched, err := filter.MatchAny(key, watchList)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t} else if !matched {\n\t\t\tcontinue\n\t\t}\n\n\t\tlog.Infof(\"Fetching block height=%d hash=%v\",\n\t\t\tblk.Height, blk.Hash)\n\n\t\trawBlock, err := c.GetBlock(&blk.Hash)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif !blockFilterer.FilterBlock(rawBlock) {\n\t\t\tcontinue\n\t\t}\n\n\t\t// If any external or internal addresses were detected in this\n\t\t// block, we return them to the caller so that the rescan\n\t\t// windows can widened with subsequent addresses. The\n\t\t// `BatchIndex` is returned so that the caller can compute the\n\t\t// *next* block from which to begin again.\n\t\tresp := &FilterBlocksResponse{\n\t\t\tBatchIndex: uint32(i),\n\t\t\tBlockMeta: blk,\n\t\t\tFoundExternalAddrs: blockFilterer.FoundExternal,\n\t\t\tFoundInternalAddrs: blockFilterer.FoundInternal,\n\t\t\tFoundOutPoints: blockFilterer.FoundOutPoints,\n\t\t\tRelevantTxns: blockFilterer.RelevantTxns,\n\t\t}\n\n\t\treturn resp, nil\n\t}\n\n\t// No addresses were found for this range.\n\treturn nil, nil\n}", "func (_Rootchain *RootchainCaller) HeaderBlocks(opts *bind.CallOpts, arg0 *big.Int) (struct {\n\tRoot [32]byte\n\tStart *big.Int\n\tEnd *big.Int\n\tCreatedAt *big.Int\n\tProposer common.Address\n}, error) {\n\tret := new(struct {\n\t\tRoot [32]byte\n\t\tStart *big.Int\n\t\tEnd *big.Int\n\t\tCreatedAt *big.Int\n\t\tProposer common.Address\n\t})\n\tout := ret\n\terr := _Rootchain.contract.Call(opts, out, \"headerBlocks\", arg0)\n\treturn *ret, err\n}", "func SeriesBlockToMultiSeriesBlocks(multiNamespaceSeriesList []MultiNamespaceSeries, seriesIteratorsPool encoding.MutableSeriesIteratorsPool) (MultiSeriesBlocks, error) {\n\t// todo(braskin): validate blocks size and aligment per namespace before creating []MultiNamespaceSeries\n\tvar multiSeriesBlocks MultiSeriesBlocks\n\tfor multiNamespaceSeriesIdx, multiNamespaceSeries := range multiNamespaceSeriesList {\n\t\tconsolidatedSeriesBlocks, err := newConsolidatedSeriesBlocks(multiNamespaceSeries, seriesIteratorsPool)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// once we get the length of consolidatedSeriesBlocks, we can create a\n\t\t// MultiSeriesBlocks list with the proper size\n\t\tif multiNamespaceSeriesIdx == 0 {\n\t\t\tmultiSeriesBlocks = make(MultiSeriesBlocks, len(consolidatedSeriesBlocks))\n\t\t}\n\n\t\tfor consolidatedSeriesBlockIdx, consolidatedSeriesBlock := range consolidatedSeriesBlocks {\n\t\t\t// we only want to set the start and end times once\n\t\t\tif multiNamespaceSeriesIdx == 0 {\n\t\t\t\tmultiSeriesBlocks[consolidatedSeriesBlockIdx].Start = consolidatedSeriesBlock.Start\n\t\t\t\tmultiSeriesBlocks[consolidatedSeriesBlockIdx].End = consolidatedSeriesBlock.End\n\t\t\t}\n\n\t\t\tif !consolidatedSeriesBlock.beyondBounds(multiSeriesBlocks[consolidatedSeriesBlockIdx]) {\n\t\t\t\treturn nil, errBlocksMisaligned\n\t\t\t}\n\n\t\t\tmultiSeriesBlocks[consolidatedSeriesBlockIdx].Blocks = append(multiSeriesBlocks[consolidatedSeriesBlockIdx].Blocks, consolidatedSeriesBlock)\n\t\t}\n\t}\n\n\treturn multiSeriesBlocks, nil\n}", "func (hlr *HandlerEnv) GetBlockWrites(c *gin.Context) {\n\tvar err error\n\tvar blkWrts []mdl.BlockWrite\n\tvar rsp = make(map[string]interface{})\n\n\t// Fetch the block writes from the database\n\topts := options.Find().SetSort(bson.D{{\"manifest.timestamp\", -1}})\n\tcsr, err := hlr.CollBlockWrites.Find(context.TODO(), bson.M{\"deleted\": bson.M{\"$ne\": true}}, opts)\n\tif err != nil {\n\t\t// error fetching blockwrites from the database\n\t\tlog.Printf(\"ERROR: %v - error fetching blockwrites from the database. See: %v\\n\",\n\t\t\tutils.FileLine(),\n\t\t\terr)\n\t\trsp[\"msg\"] = \"an error occurred, please try again\"\n\t\tc.JSON(http.StatusInternalServerError, rsp)\n\t\treturn\n\t}\n\n\t// Grab all blockwrites from the query\n\terr = csr.All(context.TODO(), &blkWrts)\n\tif err != nil {\n\t\t// error accessing blockwrite data\n\t\tlog.Printf(\"ERROR: %v - error accessing blockwrite data. See: %v\\n\",\n\t\t\tutils.FileLine(),\n\t\t\terr)\n\t\trsp[\"msg\"] = \"an error occurred, please try again\"\n\t\tc.JSON(http.StatusInternalServerError, rsp)\n\t\treturn\n\t}\n\n\t// Iterate through the query results and construct a response\n\tvar tmpCntArr []map[string]interface{}\n\tfor _, elm := range blkWrts {\n\t\tvar tmpCnt = make(map[string]interface{})\n\n\t\t// Construct a response array element\n\t\ttmpCnt[\"docid\"] = elm.RequestID\n\t\ttmpCnt[\"source\"] = elm.Source\n\t\ttmpCnt[\"event\"] = elm.Event\n\t\ttmpCnt[\"network\"] = elm.ChainNetwork\n\t\ttmpCnt[\"timestamp\"] = fmt.Sprintf(\"%v CST\", elm.Manifest.TimeStamp[:19])\n\t\ttmpCnt[\"block\"] = elm.BlockNumber\n\t\ttmpCnt[\"explorer_link\"] = fmt.Sprintf(\"%vblock/%v\",\n\t\t\tconfig.Consts[\"gochain_testnet_explorer\"],\n\t\t\telm.BlockNumber)\n\n\t\ttmpCnt[\"alert\"] = \"none\"\n\t\t// Set \"alert\" to highlight rows in the client\n\t\tif strings.Contains(strings.ToLower(elm.Event), \"alert\") {\n\t\t\ttmpCnt[\"alert\"] = \"alert\"\n\t\t}\n\n\t\t// Add element to the response\n\t\ttmpCntArr = append(tmpCntArr, tmpCnt)\n\t}\n\n\t// Construct the final response\n\trsp[\"msg\"] = \"blockwrites\"\n\trsp[\"content\"] = tmpCntArr\n\n\tc.JSON(http.StatusOK, rsp)\n}", "func New() *Blockstream {\n\treturn &Blockstream{}\n}", "func (m *GetBlocksMessage) GetBlockLocator() []*bc.Hash {\n\tblockLocator := []*bc.Hash{}\n\tfor _, rawHash := range m.RawBlockLocator {\n\t\thash := bc.NewHash(rawHash)\n\t\tblockLocator = append(blockLocator, &hash)\n\t}\n\treturn blockLocator\n}", "func (client *Client) QueryBlocks(query *Query) (*Response, error) {\n\tpath := \"/block\"\n\turi := fmt.Sprintf(\"%s%s\", client.apiBaseURL, path)\n\n\treq, err := http.NewRequest(\"GET\", uri, bytes.NewBuffer([]byte(\"\")))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbuildQuery(req, query)\n\tresp, err := client.performRequest(req, \"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar results map[string][]Block\n\terr = json.Unmarshal(resp.Response.([]byte), &results)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp.Response = results\n\treturn resp, err\n}", "func (p *PageListOrderedItemBlocks) MapBlocks() (value PageBlockClassArray) {\n\treturn PageBlockClassArray(p.Blocks)\n}", "func (core *coreService) BlockByHeight(height uint64) (*apitypes.BlockWithReceipts, error) {\n\treturn core.getBlockByHeight(height)\n}", "func getBlock(res rpc.GetBlockResponse) (GetBlockResponse, error) {\n\ttxs := make([]GetBlockTransaction, 0, len(res.Result.Transactions))\n\tfor _, rTx := range res.Result.Transactions {\n\t\tdata, ok := rTx.Transaction.([]interface{})\n\t\tif !ok {\n\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"failed to cast raw response to []interface{}\")\n\t\t}\n\t\tif data[1] != string(rpc.GetTransactionConfigEncodingBase64) {\n\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"encoding mistmatch\")\n\t\t}\n\t\trawTx, err := base64.StdEncoding.DecodeString(data[0].(string))\n\t\tif err != nil {\n\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"failed to base64 decode data, err: %v\", err)\n\t\t}\n\t\ttx, err := types.TransactionDeserialize(rawTx)\n\t\tif err != nil {\n\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"failed to deserialize transaction, err: %v\", err)\n\t\t}\n\n\t\tvar transactionMeta *TransactionMeta\n\t\tif rTx.Meta != nil {\n\t\t\tinnerInstructions := make([]TransactionMetaInnerInstruction, 0, len(rTx.Meta.InnerInstructions))\n\t\t\tfor _, metaInnerInstruction := range rTx.Meta.InnerInstructions {\n\t\t\t\tcompiledInstructions := make([]types.CompiledInstruction, 0, len(metaInnerInstruction.Instructions))\n\t\t\t\tfor _, innerInstruction := range metaInnerInstruction.Instructions {\n\t\t\t\t\tdata, err := base58.Decode(innerInstruction.Data)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"failed to base58 decode data, data: %v, err: %v\", innerInstruction.Data, err)\n\t\t\t\t\t}\n\t\t\t\t\tcompiledInstructions = append(compiledInstructions, types.CompiledInstruction{\n\t\t\t\t\t\tProgramIDIndex: innerInstruction.ProgramIDIndex,\n\t\t\t\t\t\tAccounts: innerInstruction.Accounts,\n\t\t\t\t\t\tData: data,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tinnerInstructions = append(innerInstructions, TransactionMetaInnerInstruction{\n\t\t\t\t\tIndex: metaInnerInstruction.Index,\n\t\t\t\t\tInstructions: compiledInstructions,\n\t\t\t\t})\n\t\t\t}\n\t\t\ttransactionMeta = &TransactionMeta{\n\t\t\t\tErr: rTx.Meta.Err,\n\t\t\t\tFee: rTx.Meta.Fee,\n\t\t\t\tPreBalances: rTx.Meta.PreBalances,\n\t\t\t\tPostBalances: rTx.Meta.PostBalances,\n\t\t\t\tPreTokenBalances: rTx.Meta.PreTokenBalances,\n\t\t\t\tPostTokenBalances: rTx.Meta.PostTokenBalances,\n\t\t\t\tLogMessages: rTx.Meta.LogMessages,\n\t\t\t\tInnerInstructions: innerInstructions,\n\t\t\t}\n\t\t}\n\n\t\ttxs = append(txs,\n\t\t\tGetBlockTransaction{\n\t\t\t\tMeta: transactionMeta,\n\t\t\t\tTransaction: tx,\n\t\t\t},\n\t\t)\n\t}\n\treturn GetBlockResponse{\n\t\tBlockhash: res.Result.Blockhash,\n\t\tBlockTime: res.Result.BlockTime,\n\t\tBlockHeight: res.Result.BlockHeight,\n\t\tPreviousBlockhash: res.Result.PreviousBlockhash,\n\t\tParentSLot: res.Result.ParentSLot,\n\t\tRewards: res.Result.Rewards,\n\t\tTransactions: txs,\n\t}, nil\n}", "func (a *IqnpoolApiService) GetIqnpoolBlockList(ctx context.Context) ApiGetIqnpoolBlockListRequest {\n\treturn ApiGetIqnpoolBlockListRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (bc BlockChain) deserializeBlock(o []byte) *Block {\r\n\tif !json.Valid(o) {\r\n\t\tpanic(\"Input is not a valid json object for block\")\r\n\t}\r\n\r\n\tvar jsonBlock Block\r\n\tvar b Block\r\n\t/**\r\n\tdec := json.NewDecoder(strings.NewReader(string(\to)))\r\n\tif err := dec.Decode(&jsonBlock); err == io.EOF {\r\n\t} else if err != nil {\r\n\t\tlog.Fatal(err)\r\n\t}\r\n\t**/\r\n\terr := json.Unmarshal(o, &jsonBlock)\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\t//fmt.Println(\"new block is \" + jsonBlock.Serialize())\r\n\r\n\tbalances := make(map[string]int)\r\n\tchainLength := jsonBlock.ChainLength\r\n\ttimestamp := jsonBlock.Timestamp\r\n\r\n\tif jsonBlock.IsGenesisBlock() {\r\n\t\t//fmt.Println(\"setting balances\")\r\n\t\t//fmt.Println(jsonBlock.Balances)\r\n\t\tfor client, amount := range jsonBlock.Balances {\r\n\t\t\tbalances[client] = amount\r\n\t\t}\r\n\t\tb.Balances = balances\r\n\t} else {\r\n\t\tprevBlockHash := jsonBlock.PrevBlockHash\r\n\t\tproof := jsonBlock.Proof\r\n\t\trewardAddr := jsonBlock.RewardAddr\r\n\t\ttransactions := make(map[string]*Transaction)\r\n\t\tif jsonBlock.Transactions != nil {\r\n\t\t\tfor id, tx := range jsonBlock.Transactions {\r\n\t\t\t\ttransactions[id] = tx\r\n\t\t\t}\r\n\t\t}\r\n\t\t//GOTTA FIX THIS WHEN YOU IMPLEMENT CONSTANTS\r\n\t\tb = *bc.MakeBlock(rewardAddr, nil, nil, nil)\r\n\t\tb.ChainLength = chainLength\r\n\t\tb.Timestamp = timestamp\r\n\t\tb.PrevBlockHash = prevBlockHash\r\n\t\tb.Proof = proof\r\n\t\tb.Transactions = transactions\r\n\t}\r\n\treturn &b\r\n}", "func (c *RpcClient) GetBlocksWithConfig(ctx context.Context, startSlot uint64, endSlot uint64, cfg GetBlocksConfig) (GetBlocksResponse, error) {\n\treturn c.processGetBlocks(c.Call(ctx, \"getBlocks\", startSlot, endSlot, cfg))\n}", "func (be *ContentEnc) MergeBlocks(oldData []byte, newData []byte, offset int) []byte {\n\n\t// Make block of maximum size\n\tout := make([]byte, be.plainBS)\n\n\t// Copy old and new data into it\n\tcopy(out, oldData)\n\tl := len(newData)\n\tcopy(out[offset:offset+l], newData)\n\n\t// Crop to length\n\toutLen := len(oldData)\n\tnewLen := offset + len(newData)\n\tif outLen < newLen {\n\t\toutLen = newLen\n\t}\n\treturn out[0:outLen]\n}", "func (log *PbftLog) Blocks() mapset.Set {\n\treturn log.blocks\n}", "func (rt *recvTxOut) Block() *BlockDetails {\n\treturn rt.block\n}", "func (b *Builder) Block() *Builder {\n\treturn new(Builder)\n}", "func (s *BlocksService) Get(ctx context.Context, id string) (*GetBlock, *http.Response, error) {\n\tquery := &BlockIdQuery{Id: id}\n\n\tvar responseStruct *GetBlock\n\tresp, err := s.client.SendRequest(ctx, \"GET\", \"blocks/get\", query, &responseStruct)\n\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn responseStruct, resp, err\n}", "func GetRbBlocks1() int64 {\r\n\treturn SysInt64(RbBlocks1)\r\n}", "func NewBlock(statements []sql.Node) *Block {\n\treturn &Block{statements: statements}\n}", "func (m *GetHeadersMessage) GetBlockLocator() []*bc.Hash {\n\tblockLocator := []*bc.Hash{}\n\tfor _, rawHash := range m.RawBlockLocator {\n\t\thash := bc.NewHash(rawHash)\n\t\tblockLocator = append(blockLocator, &hash)\n\t}\n\treturn blockLocator\n}", "func (tt *BlockTestTable) GetAll() []TypedBlock {\n\tvar result []TypedBlock\n\tfor _, b := range tt.AccountBlocks {\n\t\tresult = append(result, TypedBlock{\n\t\t\tAccountBlock: b,\n\t\t\tT: \"account\",\n\t\t})\n\t}\n\tfor _, b := range tt.SwapBlocks {\n\t\tresult = append(result, TypedBlock{\n\t\t\tSwapBlock: b,\n\t\t\tT: \"swap\",\n\t\t})\n\t}\n\tfor _, b := range tt.OrderBlocks {\n\t\tresult = append(result, TypedBlock{\n\t\t\tOrderBlock: b,\n\t\t\tT: \"order\",\n\t\t})\n\t}\n\treturn result\n}", "func (_Rootchain *RootchainSession) HeaderBlocks(arg0 *big.Int) (struct {\n\tRoot [32]byte\n\tStart *big.Int\n\tEnd *big.Int\n\tCreatedAt *big.Int\n\tProposer common.Address\n}, error) {\n\treturn _Rootchain.Contract.HeaderBlocks(&_Rootchain.CallOpts, arg0)\n}", "func (b *BlockRaw) ToBlock() (*Block, StdError) {\n\tvar (\n\t\tNumber uint64\n\t\tAvgTime int64\n\t\tTxcounts uint64\n\t\tTransactions []TransactionInfo\n\t\terr error\n\t)\n\tif Number, err = strconv.ParseUint(b.Number, 0, 64); err != nil {\n\t\tlogger.Error(err)\n\t\treturn nil, NewSystemError(err)\n\t}\n\tif strings.Index(b.AvgTime, \"0x\") == 0 || strings.Index(b.AvgTime, \"-0x\") == 0 {\n\t\tb.AvgTime = strings.Replace(b.AvgTime, \"0x\", \"\", 1)\n\t}\n\tif AvgTime, err = strconv.ParseInt(b.AvgTime, 16, 64); err != nil {\n\t\tlogger.Error(err)\n\t\treturn nil, NewSystemError(err)\n\t}\n\tif Txcounts, err = strconv.ParseUint(b.TxCounts, 0, 64); err != nil {\n\t\tlogger.Error(err)\n\t\treturn nil, NewSystemError(err)\n\t}\n\tfor _, t := range b.Transactions {\n\t\ttransactionInfo, err := t.ToTransaction()\n\t\tif err != nil {\n\t\t\tlogger.Error(err)\n\t\t\treturn nil, NewSystemError(err)\n\t\t}\n\t\tTransactions = append(Transactions, *transactionInfo)\n\t}\n\treturn &Block{\n\t\tVersion: b.Version,\n\t\tNumber: Number,\n\t\tHash: b.Hash,\n\t\tParentHash: b.ParentHash,\n\t\tWriteTime: b.WriteTime,\n\t\tAvgTime: AvgTime,\n\t\tTxCounts: Txcounts,\n\t\tMerkleRoot: b.MerkleRoot,\n\t\tTransactions: Transactions,\n\t}, nil\n}", "func (r *Replicator) FetchBlocks(ctx context.Context) error {\n\theight, err := r.storage.Height(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tr.l.WithFields(logrus.Fields{\n\t\t\"height\": height,\n\t}).Info(\"Fetching blocks\")\n\tresp, err := r.GrpcClient.GetBlocks(ctx, &ccmsg.GetBlocksRequest{\n\t\tStartDepth: int64(height),\n\t\tLimit: 5,\n\t})\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to fetch blocks\")\n\t}\n\n\tif len(resp.Blocks) == 0 {\n\t\tr.l.Info(\"No new blocks\")\n\t}\n\n\tfor _, block := range resp.Blocks {\n\t\tr.l.WithFields(logrus.Fields{\n\t\t\t\"height\": height,\n\t\t}).Info(\"Appending block\")\n\t\tif _, err := r.storage.AddBlock(ctx, block); err != nil {\n\t\t\treturn err\n\t\t}\n\t\theight++\n\t}\n\n\treturn nil\n}", "func mockBlock(height uint32, txs ...*types.Transaction) *types.Block {\n\treturn &types.Block{\n\t\tHeader: types.Header{\n\t\t\tHeight: height,\n\t\t},\n\t\tTransactions: txs,\n\t}\n}", "func (blockChain *BlockChain) Get(height int32) []Block {\n\treturn blockChain.Chain[height]\n}", "func MockBlock(txs []*types.Tx) *types.Block {\n\treturn &types.Block{\n\t\tBlockHeader: types.BlockHeader{Timestamp: uint64(time.Now().Nanosecond())},\n\t\tTransactions: txs,\n\t}\n}", "func NewBlock(object dbus.BusObject) *Block {\n\treturn &Block{object}\n}", "func (o SecurityGroupRuleOutput) CidrBlocks() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *SecurityGroupRule) pulumi.StringArrayOutput { return v.CidrBlocks }).(pulumi.StringArrayOutput)\n}", "func NewBlockchain(chain ...Block) *Blockchain {\n\treturn &Blockchain{chain}\n}", "func (b *indexBlock) Blocks() ([]blockHandle, error) {\n\tvar lastKey []byte\n\tkb := make([]byte, 0, MaxSstKeySize)\n\tvar blocks []blockHandle\n\n\tfor b.r.Len() > 0 {\n\t\teKey, err := prefixDecodeFrom(b.r, lastKey, kb)\n\t\tlastKey = eKey\n\t\tif _, err := binary.ReadUvarint(b.r); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbh, err := newBlockHandle(b.r)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tblocks = append(blocks, bh)\n\t}\n\n\treturn blocks, nil\n}", "func (l *Ledger) Dump() ([][]string, error) {\n\tl.mutex.RLock()\n\tdefer l.mutex.RUnlock()\n\tit := l.baseDB.NewIteratorWithPrefix([]byte(pb.BlocksTablePrefix))\n\tdefer it.Release()\n\tblocks := make([][]string, l.meta.TrunkHeight+1)\n\tfor it.Next() {\n\t\tblock := &pb.InternalBlock{}\n\t\tparserErr := proto.Unmarshal(it.Value(), block)\n\t\tif parserErr != nil {\n\t\t\treturn nil, parserErr\n\t\t}\n\t\theight := block.Height\n\t\tblockid := fmt.Sprintf(\"{ID:%x,TxCount:%d,InTrunk:%v, Tm:%d, Miner:%s}\", block.Blockid, block.TxCount, block.InTrunk, block.Timestamp/1000000000, block.Proposer)\n\t\tblocks[height] = append(blocks[height], blockid)\n\t}\n\treturn blocks, nil\n}", "func (a *insight) NewBlock(id interface{}) *block {\n\tb := new(block)\n\tb.insight = a\n\tswitch v := id.(type) {\n\tcase int:\n\t\tb.Height = int(v)\n\t\tb.hash()\n\t\tb.pages()\n\t\tb.info()\n\t\treturn b\n\tcase string:\n\t\tb.Hash = string(v)\n\t\tb.pages()\n\t\tb.info()\n\t\treturn b\n\tcase nil:\n\t\treturn b.latestBlock()\n\t}\n\treturn nil\n}", "func (synckerManager *SynckerManager) GetS2BBlocksForBeaconValidator(bestViewShardHash map[byte]common.Hash, list map[byte][]common.Hash) (map[byte][]interface{}, error) {\n\ts2bPoolLists := synckerManager.GetS2BBlocksForBeaconProducer(bestViewShardHash, list)\n\n\tmissingBlocks := compareLists(s2bPoolLists, list)\n\t// synckerManager.config.Server.\n\tif len(missingBlocks) > 0 {\n\t\tctx, _ := context.WithTimeout(context.Background(), 5*time.Second)\n\t\tsynckerManager.StreamMissingShardToBeaconBlock(ctx, missingBlocks)\n\t\t//fmt.Println(\"debug finish stream missing s2b block\")\n\n\t\ts2bPoolLists = synckerManager.GetS2BBlocksForBeaconProducer(bestViewShardHash, list)\n\t\tmissingBlocks = compareLists(s2bPoolLists, list)\n\t\tif len(missingBlocks) > 0 {\n\t\t\treturn nil, errors.New(\"Unable to sync required block in time\")\n\t\t}\n\t}\n\n\tfor sid, heights := range list {\n\t\tif len(s2bPoolLists[sid]) != len(heights) {\n\t\t\treturn nil, fmt.Errorf(\"S2BPoolLists not match sid:%v pool:%v producer:%v\", sid, len(s2bPoolLists[sid]), len(heights))\n\t\t}\n\t}\n\n\treturn s2bPoolLists, nil\n}", "func (b *logEventBuffer) getBlocksInRange(start, end int) []fetchedBlock {\n\tvar blocksInRange []fetchedBlock\n\tstart, end = b.normalRange(start, end)\n\tif start == -1 || end == -1 {\n\t\t// invalid range\n\t\treturn blocksInRange\n\t}\n\tif start < end {\n\t\treturn b.blocks[start:end]\n\t}\n\t// in case we get circular range such as [0, 1, end, ... , start, ..., size-1]\n\t// we need to return the blocks in two ranges: [start, size-1] and [0, end]\n\tblocksInRange = append(blocksInRange, b.blocks[start:]...)\n\tblocksInRange = append(blocksInRange, b.blocks[:end]...)\n\n\treturn blocksInRange\n}", "func (s Store) GetBlock (hash string) (*types.FullSignedBlock, error) {\r\n\t// Open badger\r\n\tstor, err := badger.Open(badger.DefaultOptions(s.StorFileLocation))\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\r\n\tdefer stor.Close()\r\n\r\n\tvar block types.FullSignedBlock\r\n\terr = stor.Update(func(txn *badger.Txn) error {\r\n\t\tbytes, err := readStringIndex (txn, hash, HashKeyPrefix)\r\n\t\tif err != nil{\r\n\t\t\treturn err\r\n\t\t}\r\n\t\terr = json.Unmarshal(bytes, &block)\r\n\r\n\t\treturn err\r\n\t})\r\n\r\n\treturn &block, err\r\n}", "func (s *BlockService) List(limit int, cursor string) (models.BlockPage, error) {\n\tif limit > 100 {\n\t\tlimit = 100\n\t}\n\tif limit == 0 {\n\t\tlimit = 10\n\t}\n\treturn s.dao.Find(bson.M{}, limit, cursor)\n}", "func (c *Client) GetBlocksByHeight(before, after uint64, noempty bool) (blocks *rpctypes.ResultBlockchainInfo, err error) {\n\tblocks = new(rpctypes.ResultBlockchainInfo)\n\tp := params{}\n\tif after > 0 {\n\t\tp[\"after\"] = after\n\t}\n\tif noempty {\n\t\tp[\"filter\"] = \"noempty\"\n\t}\n\terr = c.get(blocks, c.URLP(\n\t\tp,\n\t\t\"block/before/%d\", before,\n\t))\n\terr = errors.Wrap(err, \"getting blocks by height\")\n\treturn\n}", "func Block(statements ...ast.Stmt) *ast.BlockStmt {\n\treturn &ast.BlockStmt{\n\t\tList: statements,\n\t\tRbrace: statements[len(statements)-1].End(),\n\t}\n}", "func (_Rootchain *RootchainCallerSession) HeaderBlocks(arg0 *big.Int) (struct {\n\tRoot [32]byte\n\tStart *big.Int\n\tEnd *big.Int\n\tCreatedAt *big.Int\n\tProposer common.Address\n}, error) {\n\treturn _Rootchain.Contract.HeaderBlocks(&_Rootchain.CallOpts, arg0)\n}", "func Block(ctx context.Context, opts Opts) schema.Block {\n\treturn schema.SingleNestedBlock{\n\t\tAttributes: attributesMap(opts),\n\t\tCustomType: Type{\n\t\t\tObjectType: types.ObjectType{\n\t\t\t\tAttrTypes: attrTypesMap(opts),\n\t\t\t},\n\t\t},\n\t}\n}", "func GetBlock(x uint64) block.Block{\r\n\t\tvar block1 block.MinBlock\r\n\t\tvar block2 block.Block\r\n\t\tblock1.BlockNumber = x\r\n\t\tblock1.ChainYear = ChainYear\r\n\t\tfmt.Println(\"ChainYear\", block1.ChainYear)\r\n\t\tdata, err:= json.Marshal(block1)\r\n\t\tif err !=nil{\r\n\t\t\tfmt.Println(\"Error Reading Block\", err)\r\n\t\t}\r\n\t\tfmt.Println(\"Block as Json\", data)\r\n\t\ttheNodes := GetNodes(block1.BlockHash())\r\n\t\t\r\n\t\tcall := \"getBlock\"\r\n\t\t\r\n\t\tfor x:=0; x < len(theNodes); x +=1{\r\n\t\t\t\t\r\n\t\t\turl1 := \"http://\"+ MyNode.Ip+ MyNode.Port+\"/\"+ call\r\n\t\t\tfmt.Println(\"url:\", url1)\r\n\t\t\t resp, err := http.Post(url1, \"application/json\", bytes.NewBuffer(data))\r\n\r\n\t\t\tif err != nil {\r\n\t\t\t\tfmt.Println(\"Error connectig to node trying next node \", err)\r\n\t\t\t}else{\r\n\t\t\t\tfmt.Println(\"Block as Json\", data)\r\n\t\t\t\tjson.NewDecoder(resp.Body).Decode(&block2)\r\n\t\t\t\treturn block2\r\n\t\t\t}\r\n\t\t}\r\nreturn block2\r\n\t\t\r\n\t\t\r\n}", "func (gw *Gateway) GetBlocksInRange(start, end uint64) ([]coin.SignedBlock, error) {\n\tvar blocks []coin.SignedBlock\n\tvar err error\n\tgw.strand(\"GetBlocksInRange\", func() {\n\t\tblocks, err = gw.v.GetBlocksInRange(start, end)\n\t})\n\treturn blocks, err\n}", "func (gw *Gateway) GetBlocks(seqs []uint64) ([]coin.SignedBlock, error) {\n\tvar blocks []coin.SignedBlock\n\tvar err error\n\tgw.strand(\"GetBlocks\", func() {\n\t\tblocks, err = gw.v.GetBlocks(seqs)\n\t})\n\treturn blocks, err\n}", "func (c *Client) BlockAfterByHeight(height int64) ([]ExplorerBlockViewModel, error) {\n\ttimeout := time.Duration(10 * time.Second)\n\tclient := http.Client{\n\t\tTimeout: timeout,\n\t}\n\n\tpayload, err := json.Marshal(map[string]int64{\"height\": height})\n\tif err != nil {\n\t\treturn []ExplorerBlockViewModel{}, err\n\t}\n\n\tc.URL.Path = \"/local/chain/blocks-after\"\n\treq, err := c.buildReq(nil, payload, http.MethodPost)\n\tif err != nil {\n\t\treturn []ExplorerBlockViewModel{}, err\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn []ExplorerBlockViewModel{}, err\n\t}\n\tdefer resp.Body.Close()\n\tbyteArray, err := ioutil.ReadAll(resp.Body)\n\tif resp.StatusCode != 200 {\n\t\terr := errors.New(string(byteArray))\n\t\treturn []ExplorerBlockViewModel{}, err\n\t}\n\n\tvar data struct {\n\t\tDatas []ExplorerBlockViewModel `json:\"data\"`\n\t}\n\tif err := json.Unmarshal(byteArray, &data); err != nil {\n\t\treturn []ExplorerBlockViewModel{}, err\n\t}\n\treturn data.Datas, nil\n}", "func (b *Block) Get(input *BlockInput) (*Block, error) {\n\tresp, err := b.c.Request(http.MethodGet, fmt.Sprintf(\"/blocks/%s\", input.ID), new(bytes.Buffer), nil)\n\tif err != nil {\n\t\treturn &Block{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar block *Block\n\terr = json.NewDecoder(resp.Body).Decode(&block)\n\tif err != nil {\n\t\treturn &Block{}, err\n\t}\n\treturn block, nil\n}", "func (s *Server) List(ctx context.Context, in *proto.GetBlockRequest) (*proto.GetBlockResponse, error) {\n\ti, err := metrics.Gauge(\"List\", func() (interface{}, error) {\n\t\tresp := new(proto.GetBlockResponse)\n\n\t\tfor _, b := range s.Blockchain.Blocks {\n\t\t\tresp.Blocks = append(resp.Blocks, &proto.Block{\n\t\t\t\tPrevBlockHash: b.PrevBlockHash,\n\t\t\t\tData: b.Data,\n\t\t\t\tHash: b.Hash,\n\t\t\t})\n\t\t}\n\n\t\treturn resp, nil\n\t})\n\treturn i.(*proto.GetBlockResponse), err\n}", "func BlockBakingRights(b models.Block) *genModels.BakingRightsPerBlock {\n\tbr := genModels.BakingRightsPerBlock{Baker: b.Baker, Level: b.Level.Int64, BlockHash: b.Hash.String, BakerPriority: b.Priority.Ptr()}\n\tbr.Rights = BakingRights(b.BakingRights)\n\treturn &br\n}", "func NewBlock() *Block {\n\treturn &Block{}\n}", "func TestBlocklist() *blocklist.Blocklist {\n\tlist := NewTestBlocklist()\n\n\tif err := list.Save(); err != nil {\n\t\tlog.Panic(\"error saving test blocklist: \", err.Error())\n\t}\n\n\treturn list\n}", "func (a *API) GetBlockRlp(number uint64) (hexutil.Bytes, error) {\n\tblock, err := a.backend.BlockByNumber(rpctypes.BlockNumber(number))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn rlp.EncodeToBytes(block)\n}", "func New(storage Storage) *Block {\n\tb := Block{\n\t\tstorage: storage,\n\t}\n\tb.Transactions = make([]transaction.Transaction, 0, 0)\n\treturn &b\n}", "func DeserializeBlock(serializedBlock []byte) *Block {\n\tvar block Block\n\n\tdecoder := gob.NewDecoder(bytes.NewReader(serializedBlock))\n\tdecoder.Decode(&block)\n\n\treturn &block\n}", "func NewGetBlocksMessage(blockLocator []*bc.Hash, stopHash *bc.Hash) *GetBlocksMessage {\n\tmsg := &GetBlocksMessage{\n\t\tRawStopHash: stopHash.Byte32(),\n\t}\n\tfor _, hash := range blockLocator {\n\t\tmsg.RawBlockLocator = append(msg.RawBlockLocator, hash.Byte32())\n\t}\n\treturn msg\n}", "func getBlock(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {\n\n\thash, err := chainhash.NewHashFromStr(ps.ByName(\"hash\"))\n\tif err != nil {\n\t\tlog.Printf(\"could not convert string to hash: %s\\n\", err)\n\t}\n\n\tblock, err := dao.GetBlock(hash)\n\tif err != nil {\n\t\tfmt.Fprintf(w, \"Not found\")\n\t\treturn\n\t}\n\t//block.Confirmations = getBlockConfirmations(block)\n\t//block.Confirmations = getBlockConfirmations(*block) // needs dynamic calculation\n\n\t//apiblock, err := insight.ConvertToInsightBlock(block)\n\n\tjson.NewEncoder(w).Encode(&block)\n}", "func (s *SetMessageSenderBlockListRequest) GetBlockList() (value BlockListClass) {\n\tif s == nil {\n\t\treturn\n\t}\n\treturn s.BlockList\n}", "func (b *Block) Body() *Body { return &Body{b.transactions, b.signs} }", "func (itr *BlocksItr) Get() (ledger.QueryResult, error) {\n\tif itr.err != nil {\n\t\treturn nil, itr.err\n\t}\n\treturn &BlockHolder{itr.nextBlockBytes}, nil\n}", "func (c *Client) BlockByHeight(height int64) (Block, error) {\n\ttimeout := time.Duration(10 * time.Second)\n\tclient := http.Client{\n\t\tTimeout: timeout,\n\t}\n\n\tpayload, err := json.Marshal(map[string]int64{\"height\": height})\n\tif err != nil {\n\t\treturn Block{}, err\n\t}\n\n\tc.URL.Path = \"/block/at/public\"\n\treq, err := c.buildReq(nil, payload, http.MethodPost)\n\tif err != nil {\n\t\treturn Block{}, err\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn Block{}, err\n\t}\n\tdefer resp.Body.Close()\n\tbyteArray, err := ioutil.ReadAll(resp.Body)\n\tif resp.StatusCode != 200 {\n\t\terr := errors.New(string(byteArray))\n\t\treturn Block{}, err\n\t}\n\n\tvar data Block\n\tif err := json.Unmarshal(byteArray, &data); err != nil {\n\t\treturn Block{}, err\n\t}\n\treturn data, nil\n}", "func Blocks(mods ...qm.QueryMod) blockQuery {\n\tmods = append(mods, qm.From(\"\\\"block\\\"\"))\n\treturn blockQuery{NewQuery(mods...)}\n}" ]
[ "0.66517174", "0.61137074", "0.6060496", "0.602393", "0.5799248", "0.57554275", "0.575131", "0.5643157", "0.5598307", "0.5551497", "0.55365604", "0.55362105", "0.5523253", "0.55167264", "0.5508807", "0.54773945", "0.54551417", "0.5453782", "0.54265654", "0.54017013", "0.53818685", "0.5380671", "0.5373953", "0.5337066", "0.5292631", "0.5261075", "0.5247651", "0.52451193", "0.51978517", "0.5185177", "0.5173542", "0.5152453", "0.5145422", "0.5141113", "0.5079533", "0.5069172", "0.50348306", "0.5027683", "0.5015273", "0.50121945", "0.49996543", "0.49879974", "0.49875718", "0.4958089", "0.495362", "0.49029714", "0.49027255", "0.48835933", "0.48753962", "0.48717535", "0.48669693", "0.48570132", "0.48529", "0.48525092", "0.48471007", "0.48460528", "0.4845479", "0.48404953", "0.48282313", "0.48269302", "0.4823273", "0.48174682", "0.48152804", "0.48124412", "0.4803201", "0.4803026", "0.4801392", "0.47930187", "0.4771898", "0.47642648", "0.47570327", "0.47567916", "0.47546145", "0.47517368", "0.47425187", "0.474021", "0.47327402", "0.47296172", "0.4719292", "0.4707597", "0.47043875", "0.4701573", "0.4700263", "0.46988285", "0.4691721", "0.4681538", "0.46808332", "0.46770248", "0.46751356", "0.46601865", "0.46599466", "0.46566957", "0.4649909", "0.46452472", "0.46373454", "0.46308485", "0.46306866", "0.46198225", "0.46178305", "0.46165496" ]
0.7300363
0
List lists all RolloutBlocks in the indexer for a given namespace.
Список отображает все RolloutBlocks в индексаторе для заданного пространства имен.
func (s rolloutBlockNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.RolloutBlock, err error) { err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { ret = append(ret, m.(*v1alpha1.RolloutBlock)) }) return ret, err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s *rolloutBlockLister) List(selector labels.Selector) (ret []*v1alpha1.RolloutBlock, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.RolloutBlock))\n\t})\n\treturn ret, err\n}", "func (s *rolloutBlockLister) RolloutBlocks(namespace string) RolloutBlockNamespaceLister {\n\treturn rolloutBlockNamespaceLister{indexer: s.indexer, namespace: namespace}\n}", "func (s rolloutBlockNamespaceLister) Get(name string) (*v1alpha1.RolloutBlock, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"rolloutblock\"), name)\n\t}\n\treturn obj.(*v1alpha1.RolloutBlock), nil\n}", "func (s bundleNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Bundle, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.Bundle))\n\t})\n\treturn ret, err\n}", "func NewRolloutBlockLister(indexer cache.Indexer) RolloutBlockLister {\n\treturn &rolloutBlockLister{indexer: indexer}\n}", "func (s sMBNamespaceLister) List(selector labels.Selector) (ret []*v1.SMB, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.SMB))\n\t})\n\treturn ret, err\n}", "func (s beeNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.Bee, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.Bee))\n\t})\n\treturn ret, err\n}", "func (s hookNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Hook, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.Hook))\n\t})\n\treturn ret, err\n}", "func (n *namespaceClient) List() ([]ns.Metadata, error) {\n\turl := fmt.Sprintf(\"%s%s\", n.url, nsh.GetURL)\n\tresp, err := n.client.DoHTTPRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdata := &admin.NamespaceGetResponse{}\n\tdefer func() {\n\t\tioutil.ReadAll(resp.Body)\n\t\tresp.Body.Close()\n\t}()\n\tif err := jsonpb.Unmarshal(resp.Body, data); err != nil {\n\t\treturn nil, err\n\t}\n\tnsMetas := []ns.Metadata{}\n\tfor nsID, nsOpts := range data.GetRegistry().GetNamespaces() {\n\t\tmd, err := ns.ToMetadata(nsID, nsOpts)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tnsMetas = append(nsMetas, md)\n\t}\n\tn.logger.Info(\"namespace retrieved\")\n\treturn nsMetas, nil\n}", "func (s *Server) List(ctx context.Context, in *proto.GetBlockRequest) (*proto.GetBlockResponse, error) {\n\ti, err := metrics.Gauge(\"List\", func() (interface{}, error) {\n\t\tresp := new(proto.GetBlockResponse)\n\n\t\tfor _, b := range s.Blockchain.Blocks {\n\t\t\tresp.Blocks = append(resp.Blocks, &proto.Block{\n\t\t\t\tPrevBlockHash: b.PrevBlockHash,\n\t\t\t\tData: b.Data,\n\t\t\t\tHash: b.Hash,\n\t\t\t})\n\t\t}\n\n\t\treturn resp, nil\n\t})\n\treturn i.(*proto.GetBlockResponse), err\n}", "func (h *Handler) ListByNamespace(namespace string) ([]*unstructured.Unstructured, error) {\n\tlistOptions := h.Options.ListOptions.DeepCopy()\n\tlistOptions.LabelSelector = \"\"\n\n\tif err := h.getGVRAndNamespaceScope(); err != nil {\n\t\treturn nil, err\n\t}\n\tif h.isNamespaced {\n\t\treturn extractList(h.dynamicClient.Resource(h.gvr).Namespace(namespace).List(h.ctx, *listOptions))\n\t}\n\treturn nil, fmt.Errorf(\"%s is not namespace-scoped k8s resource\", h.gvr)\n}", "func (s sensuAssetNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.SensuAsset, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.SensuAsset))\n\t})\n\treturn ret, err\n}", "func (b *Block) List(input *BlockCursorInput) (*Blocks, error) {\n\tparams := make(map[string]string)\n\tparams[\"cursor\"] = input.Cursor\n\tresp, err := b.c.Request(http.MethodGet, \"/blocks\", new(bytes.Buffer), params)\n\tif err != nil {\n\t\treturn &Blocks{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar blocks *Blocks\n\terr = json.NewDecoder(resp.Body).Decode(&blocks)\n\tif err != nil {\n\t\treturn &Blocks{}, err\n\t}\n\treturn blocks, nil\n}", "func (s awsApiGatewayBasePathMappingNamespaceLister) List(selector labels.Selector) (ret []*v1.AwsApiGatewayBasePathMapping, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.AwsApiGatewayBasePathMapping))\n\t})\n\treturn ret, err\n}", "func (s wafregionalRuleNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.WafregionalRule, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.WafregionalRule))\n\t})\n\treturn ret, err\n}", "func (s scyllaDBMonitoringNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.ScyllaDBMonitoring, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.ScyllaDBMonitoring))\n\t})\n\treturn ret, err\n}", "func (s cloudformationNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Cloudformation, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.Cloudformation))\n\t})\n\treturn ret, err\n}", "func (s logicalNetworkNamespaceLister) List(selector labels.Selector) (ret []*v1.LogicalNetwork, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.LogicalNetwork))\n\t})\n\treturn ret, err\n}", "func (c *Module) ListNS() ([]string, error) {\n\tlog.Debug().Msg(\"list namespaces\")\n\n\tclient, err := containerd.New(c.containerd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer client.Close()\n\n\tctx := context.Background()\n\treturn client.NamespaceService().List(ctx)\n}", "func (s icecreamNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Icecream, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.Icecream))\n\t})\n\treturn ret, err\n}", "func (s dynamoDBNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.DynamoDB, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.DynamoDB))\n\t})\n\treturn ret, err\n}", "func (s elasticBeanstalkConfigurationTemplateNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.ElasticBeanstalkConfigurationTemplate, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.ElasticBeanstalkConfigurationTemplate))\n\t})\n\treturn ret, err\n}", "func (s storageBucketNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.StorageBucket, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.StorageBucket))\n\t})\n\treturn ret, err\n}", "func RunList(cmd *cobra.Command, args []string) {\n\tlist := &nbv1.NamespaceStoreList{\n\t\tTypeMeta: metav1.TypeMeta{Kind: \"NamespaceStoreList\"},\n\t}\n\tif !util.KubeList(list, &client.ListOptions{Namespace: options.Namespace}) {\n\t\treturn\n\t}\n\tif len(list.Items) == 0 {\n\t\tfmt.Printf(\"No namespace stores found.\\n\")\n\t\treturn\n\t}\n\ttable := (&util.PrintTable{}).AddRow(\n\t\t\"NAME\",\n\t\t\"TYPE\",\n\t\t\"TARGET-BUCKET\",\n\t\t\"PHASE\",\n\t\t\"AGE\",\n\t)\n\tfor i := range list.Items {\n\t\tbs := &list.Items[i]\n\t\ttb, err := util.GetNamespaceStoreTargetBucket(bs)\n\t\tif err == nil {\n\t\t\ttable.AddRow(\n\t\t\t\tbs.Name,\n\t\t\t\tstring(bs.Spec.Type),\n\t\t\t\ttb,\n\t\t\t\tstring(bs.Status.Phase),\n\t\t\t\tutil.HumanizeDuration(time.Since(bs.CreationTimestamp.Time).Round(time.Second)),\n\t\t\t)\n\t\t}\n\t}\n\tfmt.Print(table.String())\n}", "func (s testRunNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.TestRun, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.TestRun))\n\t})\n\treturn ret, err\n}", "func (k8s *Client) ListNamespaces() []string {\n\treturn k8s.namespaceIndexer.ListIndexFuncValues(namespaceIndexName)\n}", "func (s monitorMetricAlertruleNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.MonitorMetricAlertrule, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.MonitorMetricAlertrule))\n\t})\n\treturn ret, err\n}", "func (s crdExampleNamespaceLister) List(selector labels.Selector) (ret []*v1.CrdExample, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.CrdExample))\n\t})\n\treturn ret, err\n}", "func (s sealedSecretNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.SealedSecret, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.SealedSecret))\n\t})\n\treturn ret, err\n}", "func (s volumeCloneSourceNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.VolumeCloneSource, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.VolumeCloneSource))\n\t})\n\treturn ret, err\n}", "func (s rBACDefinitionNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.RBACDefinition, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.RBACDefinition))\n\t})\n\treturn ret, err\n}", "func (s *bundleLister) List(selector labels.Selector) (ret []*v1alpha1.Bundle, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.Bundle))\n\t})\n\treturn ret, err\n}", "func (s clientViewNamespaceLister) List(selector labels.Selector) (ret []*v1alpha.ClientView, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha.ClientView))\n\t})\n\treturn ret, err\n}", "func (s bindingTemplateNamespaceLister) List(selector labels.Selector) (ret []*experimental.BindingTemplate, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*experimental.BindingTemplate))\n\t})\n\treturn ret, err\n}", "func (r *resource) ListWithNamespace(ns string, list runtime.Object) error {\n\terr := r.client.ControlCli.List(context.TODO(), &runtimecli.ListOptions{Namespace: ns}, list)\n\tif err != nil {\n\t\tlog.Warn(\"Failed to list resource. \", err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s elasticacheClusterNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.ElasticacheCluster, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.ElasticacheCluster))\n\t})\n\treturn ret, err\n}", "func (s kylinNodeNamespaceLister) List(selector labels.Selector) (ret []*v1.KylinNode, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.KylinNode))\n\t})\n\treturn ret, err\n}", "func (s oAuthClientNamespaceLister) List(selector labels.Selector) (ret []*api.OAuthClient, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*api.OAuthClient))\n\t})\n\treturn ret, err\n}", "func (s keyVaultKeyNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.KeyVaultKey, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.KeyVaultKey))\n\t})\n\treturn ret, err\n}", "func (s recoveryServicesProtectionContainerNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.RecoveryServicesProtectionContainer, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.RecoveryServicesProtectionContainer))\n\t})\n\treturn ret, err\n}", "func (s cognitoResourceServerNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.CognitoResourceServer, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.CognitoResourceServer))\n\t})\n\treturn ret, err\n}", "func (s genericNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Generic, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.Generic))\n\t})\n\treturn ret, err\n}", "func (s eCRRepositoryNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.ECRRepository, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.ECRRepository))\n\t})\n\treturn ret, err\n}", "func (s consumerNamespaceLister) List(selector labels.Selector) (ret []*arbv1.Consumer, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*arbv1.Consumer))\n\t})\n\treturn ret, err\n}", "func (s *API) ListNamespaces(req *ListNamespacesRequest, opts ...scw.RequestOption) (*ListNamespacesResponse, error) {\n\tvar err error\n\n\tif req.Region == \"\" {\n\t\tdefaultRegion, _ := s.client.GetDefaultRegion()\n\t\treq.Region = defaultRegion\n\t}\n\n\tdefaultPageSize, exist := s.client.GetDefaultPageSize()\n\tif (req.PageSize == nil || *req.PageSize == 0) && exist {\n\t\treq.PageSize = &defaultPageSize\n\t}\n\n\tquery := url.Values{}\n\tparameter.AddToQuery(query, \"page\", req.Page)\n\tparameter.AddToQuery(query, \"page_size\", req.PageSize)\n\tparameter.AddToQuery(query, \"order_by\", req.OrderBy)\n\tparameter.AddToQuery(query, \"organization_id\", req.OrganizationID)\n\tparameter.AddToQuery(query, \"project_id\", req.ProjectID)\n\tparameter.AddToQuery(query, \"name\", req.Name)\n\n\tif fmt.Sprint(req.Region) == \"\" {\n\t\treturn nil, errors.New(\"field Region cannot be empty in request\")\n\t}\n\n\tscwReq := &scw.ScalewayRequest{\n\t\tMethod: \"GET\",\n\t\tPath: \"/registry/v1/regions/\" + fmt.Sprint(req.Region) + \"/namespaces\",\n\t\tQuery: query,\n\t\tHeaders: http.Header{},\n\t}\n\n\tvar resp ListNamespacesResponse\n\n\terr = s.client.Do(scwReq, &resp, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resp, nil\n}", "func (client OccMetricsClient) listNamespaces(ctx context.Context, request common.OCIRequest, binaryReqBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (common.OCIResponse, error) {\n\n\thttpRequest, err := request.HTTPRequest(http.MethodGet, \"/namespaces\", binaryReqBody, extraHeaders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response ListNamespacesResponse\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/occ/20230515/NamespaceCollection/ListNamespaces\"\n\t\terr = common.PostProcessServiceError(err, \"OccMetrics\", \"ListNamespaces\", apiReferenceLink)\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func RunNamespacesListRegions(c *CmdConfig) error {\n\tif len(c.Args) > 0 {\n\t\treturn doctl.NewTooManyArgsErr(c.NS)\n\t}\n\tfmt.Fprintf(c.Out, \"%+v\\n\", getValidRegions())\n\treturn nil\n}", "func (s appsyncDatasourceNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.AppsyncDatasource, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.AppsyncDatasource))\n\t})\n\treturn ret, err\n}", "func (s democrdNamespaceLister) List(selector labels.Selector) (ret []*v1.Democrd, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.Democrd))\n\t})\n\treturn ret, err\n}", "func (s targetNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Target, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.Target))\n\t})\n\treturn ret, err\n}", "func (s awsIamPolicyAttachmentNamespaceLister) List(selector labels.Selector) (ret []*v1.AwsIamPolicyAttachment, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.AwsIamPolicyAttachment))\n\t})\n\treturn ret, err\n}", "func (s trialNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.Trial, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.Trial))\n\t})\n\treturn ret, err\n}", "func (s seaOtterNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.SeaOtter, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.SeaOtter))\n\t})\n\treturn ret, err\n}", "func (a *DefaultClient) List(l vfs.Location) ([]string, error) {\n\tURL, err := url.Parse(l.(*Location).ContainerURL())\n\tif err != nil {\n\t\treturn []string{}, err\n\t}\n\n\tcontainerURL := azblob.NewContainerURL(*URL, a.pipeline)\n\tctx := context.Background()\n\tvar list []string\n\tfor marker := (azblob.Marker{}); marker.NotDone(); {\n\t\tlistBlob, err := containerURL.ListBlobsHierarchySegment(ctx, marker, \"/\",\n\t\t\tazblob.ListBlobsSegmentOptions{Prefix: utils.RemoveLeadingSlash(l.Path())})\n\t\tif err != nil {\n\t\t\treturn []string{}, err\n\t\t}\n\n\t\tmarker = listBlob.NextMarker\n\n\t\tfor i := range listBlob.Segment.BlobItems {\n\t\t\tlist = append(list, listBlob.Segment.BlobItems[i].Name)\n\t\t}\n\t}\n\treturn list, nil\n}", "func (client IdentityClient) listTagNamespaces(ctx context.Context, request common.OCIRequest, binaryReqBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (common.OCIResponse, error) {\n\n\thttpRequest, err := request.HTTPRequest(http.MethodGet, \"/tagNamespaces\", binaryReqBody, extraHeaders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response ListTagNamespacesResponse\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\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func (s *BlockService) List(limit int, cursor string) (models.BlockPage, error) {\n\tif limit > 100 {\n\t\tlimit = 100\n\t}\n\tif limit == 0 {\n\t\tlimit = 10\n\t}\n\treturn s.dao.Find(bson.M{}, limit, cursor)\n}", "func (c *MockVirtualNetworksClient) List(ctx context.Context, resourceGroupName string) ([]network.VirtualNetwork, error) {\n\tvar l []network.VirtualNetwork\n\tfor _, vnet := range c.VNets {\n\t\tl = append(l, vnet)\n\t}\n\treturn l, nil\n}", "func (c *MockLoadBalancersClient) List(ctx context.Context, resourceGroupName string) ([]network.LoadBalancer, error) {\n\tvar l []network.LoadBalancer\n\tfor _, lb := range c.LBs {\n\t\tl = append(l, lb)\n\t}\n\treturn l, nil\n}", "func (s gameliftFleetNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.GameliftFleet, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.GameliftFleet))\n\t})\n\treturn ret, err\n}", "func (client OccMetricsClient) ListNamespaces(ctx context.Context, request ListNamespacesRequest) (response ListNamespacesResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tpolicy := common.DefaultRetryPolicy()\n\tif client.RetryPolicy() != nil {\n\t\tpolicy = *client.RetryPolicy()\n\t}\n\tif request.RetryPolicy() != nil {\n\t\tpolicy = *request.RetryPolicy()\n\t}\n\tociResponse, err = common.Retry(ctx, request, client.listNamespaces, policy)\n\tif err != nil {\n\t\tif ociResponse != nil {\n\t\t\tif httpResponse := ociResponse.HTTPResponse(); httpResponse != nil {\n\t\t\t\topcRequestId := httpResponse.Header.Get(\"opc-request-id\")\n\t\t\t\tresponse = ListNamespacesResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = ListNamespacesResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(ListNamespacesResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into ListNamespacesResponse\")\n\t}\n\treturn\n}", "func (s vulnerabilityNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Vulnerability, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.Vulnerability))\n\t})\n\treturn ret, err\n}", "func (s pipelineResourceNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.PipelineResource, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.PipelineResource))\n\t})\n\treturn ret, err\n}", "func (s ingressListenerNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.IngressListener, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.IngressListener))\n\t})\n\treturn ret, err\n}", "func (s computeRouterInterfaceNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.ComputeRouterInterface, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.ComputeRouterInterface))\n\t})\n\treturn ret, err\n}", "func (s databaseClusterNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.DatabaseCluster, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.DatabaseCluster))\n\t})\n\treturn ret, err\n}", "func (s routeGroupNamespaceLister) List(selector labels.Selector) (ret []*v1.RouteGroup, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.RouteGroup))\n\t})\n\treturn ret, err\n}", "func (s rabbitmqSourceNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.RabbitmqSource, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.RabbitmqSource))\n\t})\n\treturn ret, err\n}", "func (s knativeEventingNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.KnativeEventing, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.KnativeEventing))\n\t})\n\treturn ret, err\n}", "func (s elasticDLJobNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.ElasticDLJob, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.ElasticDLJob))\n\t})\n\treturn ret, err\n}", "func (s kogitoSourceNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.KogitoSource, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.KogitoSource))\n\t})\n\treturn ret, err\n}", "func (c *Client) Namespace(ns string, onlyLeaf bool) ([]string, error) {\n\tvar res []string\n\tfullURL := fmt.Sprintf(\"%s/router/ns?ns=%s&format=list\", c.Addr, ns)\n\tresp, err := http.Get(fullURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode/100 != 2 {\n\t\treturn nil, fmt.Errorf(\"HTTP status error: %d\", resp.Status)\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar data namespace\n\tif err := json.Unmarshal(body, &data); err != nil {\n\t\treturn nil, err\n\t}\n\n\tres = data.Data\n\n\tif !onlyLeaf {\n\t\ttmp := make(map[string]bool)\n\t\tfor _, leaf := range data.Data {\n\t\t\tarr := strings.SplitAfterN(leaf, \".\", 2)\n\t\t\tif len(arr) > 1 {\n\t\t\t\ttmp[arr[1]] = true\n\t\t\t}\n\t\t}\n\n\t\tfor k := range tmp {\n\t\t\tres = append(res, k)\n\t\t}\n\t}\n\n\treturn res, nil\n}", "func (s backendConfigNamespaceLister) List(selector labels.Selector) (ret []*v1.BackendConfig, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.BackendConfig))\n\t})\n\treturn ret, err\n}", "func (s apiGatewayModelNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.ApiGatewayModel, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.ApiGatewayModel))\n\t})\n\treturn ret, err\n}", "func (s ssmPatchGroupNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.SsmPatchGroup, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.SsmPatchGroup))\n\t})\n\treturn ret, err\n}", "func (s computeRegionInstanceGroupManagerNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.ComputeRegionInstanceGroupManager, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.ComputeRegionInstanceGroupManager))\n\t})\n\treturn ret, err\n}", "func (s *wafregionalRuleLister) List(selector labels.Selector) (ret []*v1alpha1.WafregionalRule, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.WafregionalRule))\n\t})\n\treturn ret, err\n}", "func (c *SubresourceClient) List(namespace string, labels map[string]string) (result []metav1.Object, e error) {\n\tif c.Error != \"\" {\n\t\te = fmt.Errorf(c.Error)\n\t} else {\n\t\tresult = []metav1.Object{c.Subresource}\n\t}\n\treturn\n}", "func List(client *golangsdk.ServiceClient, clusterId string) (r ListResult) {\n\t_, r.Err = client.Get(listURL(client, clusterId), &r.Body, nil)\n\treturn\n}", "func (k *KV) List(ctx context.Context, namespace, path string) ([]string, error) {\n\tpath, err := getKVPath(namespace, path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn k.b.List(ctx, path)\n}", "func (obs *Observer) List(opts metav1.ListOptions) (*unstructured.UnstructuredList, error) {\n\treturn obs.client.Namespace(obs.namespace).List(opts)\n}", "func (s routeClaimNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.RouteClaim, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.RouteClaim))\n\t})\n\treturn ret, err\n}", "func (c *sandboxes) List(ctx context.Context, opts metav1.ListOptions) (result *v1.SandboxList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = &v1.SandboxList{}\n\terr = c.client.Get().\n\t\tResource(\"sandboxes\").\n\t\tVersionedParams(&opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}", "func (h Client) list(namespace string, extraArgs ...string) (string, error) {\n\targs := []string{\"list\", \"--namespace\", namespace}\n\targs = append(args, extraArgs...)\n\tstdOut, stdErr, err := h.Exec(args...)\n\tif err != nil && stdErr != \"\" {\n\t\treturn \"\", errors.New(stdErr)\n\t}\n\treturn stdOut, nil\n}", "func (a *IqnpoolApiService) GetIqnpoolBlockList(ctx context.Context) ApiGetIqnpoolBlockListRequest {\n\treturn ApiGetIqnpoolBlockListRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (s passwordNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Password, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.Password))\n\t})\n\treturn ret, err\n}", "func (s tagRouteNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.TagRoute, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.TagRoute))\n\t})\n\treturn ret, err\n}", "func (client *NamespacesClient) GetList(limit, skip int) (*schema.Namespaces, error) {\n\tif limit <= 0 {\n\t\tlimit = 10\n\t}\n\tif skip < 0 {\n\t\tskip = 0\n\t}\n\n\tresponse, err := client.http.execute(\"GET\", fmt.Sprintf(\"%s?limit=%d&skip=%d\", endpointNamespaces, limit, skip), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnamespaces := new(schema.Namespaces)\n\tif err := json.Unmarshal(response, namespaces); err != nil {\n\t\treturn nil, err\n\t}\n\treturn namespaces, nil\n}", "func (d *namespaceHandlerImpl) ListNamespaces(\n\tctx context.Context,\n\tlistRequest *workflowservice.ListNamespacesRequest,\n) (*workflowservice.ListNamespacesResponse, error) {\n\n\tpageSize := 100\n\tif listRequest.GetPageSize() != 0 {\n\t\tpageSize = int(listRequest.GetPageSize())\n\t}\n\n\tresp, err := d.metadataMgr.ListNamespaces(ctx, &persistence.ListNamespacesRequest{\n\t\tPageSize: pageSize,\n\t\tNextPageToken: listRequest.NextPageToken,\n\t\tIncludeDeleted: listRequest.GetNamespaceFilter().GetIncludeDeleted(),\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar namespaces []*workflowservice.DescribeNamespaceResponse\n\tfor _, namespace := range resp.Namespaces {\n\t\tdesc := &workflowservice.DescribeNamespaceResponse{\n\t\t\tIsGlobalNamespace: namespace.IsGlobalNamespace,\n\t\t\tFailoverVersion: namespace.Namespace.FailoverVersion,\n\t\t}\n\t\tdesc.NamespaceInfo, desc.Config, desc.ReplicationConfig, desc.FailoverHistory =\n\t\t\td.createResponse(\n\t\t\t\tnamespace.Namespace.Info,\n\t\t\t\tnamespace.Namespace.Config,\n\t\t\t\tnamespace.Namespace.ReplicationConfig)\n\t\tnamespaces = append(namespaces, desc)\n\t}\n\n\tresponse := &workflowservice.ListNamespacesResponse{\n\t\tNamespaces: namespaces,\n\t\tNextPageToken: resp.NextPageToken,\n\t}\n\n\treturn response, nil\n}", "func (s spannerInstanceIamBindingNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.SpannerInstanceIamBinding, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.SpannerInstanceIamBinding))\n\t})\n\treturn ret, err\n}", "func (s messagingInfrastructureNamespaceLister) List(selector labels.Selector) (ret []*v1.MessagingInfrastructure, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.MessagingInfrastructure))\n\t})\n\treturn ret, err\n}", "func (c *BlockVolumeClient) List(params *BlockVolumeParams) (*BlockVolumeList, error) {\n\tlist := &BlockVolumeList{}\n\n\terr := c.Backend.CallIntoInterface(\"v1/Storage/Block/Volume/list\", params, list)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn list, nil\n}", "func RunNamespacesList(c *CmdConfig) error {\n\tif len(c.Args) > 0 {\n\t\treturn doctl.NewTooManyArgsErr(c.NS)\n\t}\n\tlist, err := c.Serverless().ListNamespaces(context.TODO())\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn c.Display(&displayers.Namespaces{Info: list.Namespaces})\n}", "func (c *MockRouteTablesClient) List(ctx context.Context, resourceGroupName string) ([]network.RouteTable, error) {\n\tvar l []network.RouteTable\n\tfor _, rt := range c.RTs {\n\t\tl = append(l, rt)\n\t}\n\treturn l, nil\n}", "func BlockStats(offset, count uint) ([]BlockStatItem, error) {\n\tjsonStats := []struct {\n\t\tDate Time `json:\"date\"`\n\t\tDifficulty uint64 `json:\"difficulty\"`\n\t\tBlockTime float64 `json:\"block_time\"`\n\t}{}\n\tif err := fetch(&jsonStats, blockStatsEndpoint, offset, count); err != nil {\n\t\treturn nil, err\n\t}\n\tstats := make([]BlockStatItem, len(jsonStats))\n\tfor i, s := range jsonStats {\n\t\tstats[i] = BlockStatItem(s)\n\t}\n\treturn stats, nil\n}", "func (s awsCustomerGatewayNamespaceLister) List(selector labels.Selector) (ret []*v1.AwsCustomerGateway, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.AwsCustomerGateway))\n\t})\n\treturn ret, err\n}", "func (s bucketRequestNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.BucketRequest, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.BucketRequest))\n\t})\n\treturn ret, err\n}", "func (c *MockNatGatewaysClient) List(ctx context.Context, resourceGroupName string) ([]network.NatGateway, error) {\n\tvar l []network.NatGateway\n\tfor _, ngw := range c.NGWs {\n\t\tl = append(l, ngw)\n\t}\n\treturn l, nil\n}", "func (s shareManagerNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.ShareManager, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.ShareManager))\n\t})\n\treturn ret, err\n}", "func (s chaosNamespaceLister) List(selector labels.Selector) (ret []*v1.Chaos, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.Chaos))\n\t})\n\treturn ret, err\n}", "func (s virtualHubNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.VirtualHub, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.VirtualHub))\n\t})\n\treturn ret, err\n}" ]
[ "0.70668423", "0.6486759", "0.59354115", "0.58971703", "0.58813244", "0.5809516", "0.5714969", "0.56303203", "0.55635107", "0.5493994", "0.5447972", "0.54354554", "0.54354066", "0.5417491", "0.53622055", "0.5223752", "0.5200587", "0.51956224", "0.5188562", "0.51839614", "0.51690185", "0.51596916", "0.51514935", "0.5148788", "0.5135959", "0.5121471", "0.5120799", "0.5108839", "0.51078004", "0.5106584", "0.51009744", "0.50907606", "0.50813645", "0.5078766", "0.5075793", "0.50652", "0.50600624", "0.50401723", "0.50324005", "0.50180435", "0.499617", "0.4990094", "0.49713722", "0.4967371", "0.496105", "0.49585378", "0.49427384", "0.49221405", "0.49217427", "0.49100912", "0.49099103", "0.48983333", "0.48940027", "0.48896435", "0.48865807", "0.48844427", "0.48744005", "0.48698214", "0.48641545", "0.48579645", "0.4840469", "0.48329124", "0.48302022", "0.48290154", "0.48283204", "0.48241305", "0.4823285", "0.48225576", "0.4809655", "0.48047125", "0.47859463", "0.47847125", "0.4783148", "0.4780255", "0.47788945", "0.47776496", "0.47769684", "0.47756767", "0.477124", "0.47645542", "0.4757949", "0.4754976", "0.47482017", "0.47452405", "0.47421414", "0.47393233", "0.47382417", "0.4735205", "0.47315958", "0.4725929", "0.4725348", "0.4724894", "0.47227582", "0.47181523", "0.4715999", "0.47148082", "0.4713132", "0.47030097", "0.46834278", "0.46811578" ]
0.81074965
0