slc

package module
v0.2.0-alpha Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 10, 2025 License: Apache-2.0 Imports: 28 Imported by: 1

README

Decombine SLC

License Apache 2 Contributor Covenant

Create Decombine Smart Legal Contracts (SLC) with the Go SDK.

Installation

slc can be installed with:

go get "github.com/decombine/slc@latest"

The contract CLI can be installed with:

go install "github.com/decombine/contract@latest"

Overview

slc is an SDK to create Decombine Smart Legal Contracts (SLC). Decombine SLC are used to perform programmatic contractual execution in a standardized, templated, and declarative way. SLC are defined as a definition file that maps different states and events with software actions to be executed. SLC are designed to be used in a GitOps workflow.

Decombine SLC were invented to offer an accessible, transparent, and cloud-native way for parties to form an agreement. SLC ensure transparency about what will happen and when. In contrast to conventional agreements where a digitized contract may be created and then all other processes are separate, an SLC instead integrates contract-related processes into an end-to-end workflow.

Decombine SLC are intended to provide:

  • Safer, predictable, and lower cost execution of agreements
  • Increased transparency and understanding throughout the lifecycle of contract execution
  • Greater accessibility to complex solutions by integrating with industry-leading open source

Decombine SLC can be run on conventional infrastructure and are currently under development for Kubernetes-native workloads. Decombine SLC are not a replacement for natural language contracts, but instead, augment conventional contracts.

Decombine SLC can be self-hosted or run on a managed service such as decombine.com.

Decombine SLC are defined as a JSON, YAML, or TOML definition that includes a State Configuration to create a Unified Modeling Language state machine. Each state in the state machine can be associated with a set of actions to be executed on entry and exit of the state. Actions will eventually be any arbitrary code, but currently development is focused on Kubernetes-native runtime.

Transitions between states are triggered by events. Events use the CloudEvents specification.

How to use

The slc package can be used to generate and validate the SLC definition and State Configuration. You can also use the contract CLI to generate and validate SLC in various formats (JSON, YAML, TOML).

SLC are designed and implemented declaratively to use GitOps. The SLC definition, contractual text references, associated policies, and actions are stored in a Git repository. The Git repository is then synchronized with a runtime environment such as Kubernetes. A remote service such as Decombine can be used to provide state synchronization, orchestration, and event handling or slc-controller can be self-hosted.

The slc-controller can be installed on Kubernetes to schedule SmartLegalContract resources and schedule the workloads defined in the SLC definition.

Contributing

Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests.

Versioning

Decombine SLC are currently under active development. slc, contract, and slc-controller are all in alpha and adhere to Semantic Versioning. The Decombine specification itself is versioned and will be updated as needed.

Resources

License

This project is licensed under the Apache License, Version 2.0 - see the LICENSE file for details.

Documentation

Index

Constants

View Source
const (
	CloudEventsVersion = "1.0"
	StrictHeaders      = false
)
View Source
const (
	// JSON is the JSON file format.
	JSON = "json"
	// YAML is the YAML file format.
	YAML = "yaml"
	// TOML is the TOML file format.
	TOML = "toml"
)
View Source
const (
	Version = "0.1.0"
)

Variables

View Source
var (
	ErrCannotUnmarshalJSON = errors.New("cannot unmarshal contract json")
	ErrCannotUnmarshalYAML = errors.New("cannot unmarshal contract yaml")
	ErrCannotUnmarshalTOML = errors.New("cannot unmarshal contract toml")
)

Functions

func NewClient

func NewClient(ctx context.Context, network Network, opts ...ConnectionOption) (*http.Client, error)

NewClient creates a new Client for a Contract Network.

func NewGitHubClient

func NewGitHubClient(token string) *gogithub.Client

func NewRegoPolicy

func NewRegoPolicy(ctx context.Context, module, query string, policyContent []byte) (*rego.PreparedEvalQuery, error)

NewRegoPolicy prepares an OPA Rego policy for evaluation that can be used within Contract State Condition.

func NewRegoPolicyFS

func NewRegoPolicyFS(ctx context.Context, module, query, path string) (*rego.PreparedEvalQuery, error)

NewRegoPolicyFS prepares an OPA Rego policy for evaluation from the local file system that can be used within Contract State Condition. This is useful for testing and development.

func NewStateMachine

func NewStateMachine(ctx context.Context, current string, c *Contract, opts ...FSMOption) (*stateless.StateMachine, error)

NewStateMachine initializes a Finite State Machine (FSM) for a given Smart Legal Contract. The FSM is constructed based on the StateConfiguration of the Contract. The FSM is set to the current State passed as an argument.

func NewTransitionContext

func NewTransitionContext(ctx context.Context, u *TransitionCtx) context.Context

NewTransitionContext returns a new Context that carries value TransitionCtx.

func StateTransitionValidator

func StateTransitionValidator(ctx context.Context, current string, ctr *Contract, tx Transition) (*stateless.StateMachine, error)

StateTransitionValidator evaluates a State Machine and a possible transition to determine if the transition is valid or not.

func ValidateRepository

func ValidateRepository(ctx context.Context, token, uri, branch, path string) (string, error)

ValidateRepository accepts a GitSource and validates the target repository exists, is accessible, and at minimum a contract.json.

Types

type Action

type Action struct {
	// The type of the action
	ActionType        string             `json:"actionType,omitempty" yaml:"actionType" toml:"actionType"`
	KubernetesActions []KubernetesAction `json:"kubernetesAction,omitempty" yaml:"kubernetesAction" toml:"kubernetesAction"`
}

type Condition

type Condition struct {
	// Name of the Condition.
	Name string `json:"name" yaml:"name" toml:"name"`
	// Value of the Condition. This may be used to represent a specific policy query.
	// E.g., "data.policy.allow"
	Value string `json:"value" yaml:"value" toml:"value"`
	// Path to the Condition logic. E.g., "./service/condition.rego"
	// Path is relative to the PolicySource.Directory.
	Path string `json:"path" yaml:"path" toml:"path"`
}

Condition is used to apply a Policy to a Smart Legal Contract State Transition. A Policy may include Open Policy Agent (OPA) Rego logic.

type ConnectionOption

type ConnectionOption func(*ConnectionOptions)

func WithJetStream

func WithJetStream(config jetstream.StreamConfig) ConnectionOption

WithJetStream is a ConnectionOption to provide a JetStream configuration for the Contract Network.

func WithSecret

func WithSecret(secret string) ConnectionOption

func WithToken

func WithToken(token string) ConnectionOption

WithToken is a ConnectionOption that changes the default behavior of the Contract Network to use a JSON Web Token (JWT).

type ConnectionOptions

type ConnectionOptions struct {
	JWT       []byte
	Secret    string
	JetStream jetstream.StreamConfig
}

ConnectionOptions holds options for configuring Contract Network connectivity.

type Contract

type Contract struct {
	// The unique identifier (UUID) of the SLC. Typically created by the Network managing the SLC.
	ID string `json:"id,omitempty" yaml:"id,omitempty" toml:"id,omitempty"`
	// The friendly Name of the SLC
	Name string `json:"name" yaml:"name" toml:"name" validate:"required"`
	// The Version of the SLC schema
	Version string `json:"version" yaml:"version" toml:"version" validate:"required,semver"`
	// Text of the SLC
	Text ContractText `json:"text" yaml:"text" toml:"text"`
	// The Source of the SLC
	Source GitSource `json:"source" yaml:"source" toml:"source"`
	// The Policy included in the SLC
	Policy PolicySource `json:"policy" yaml:"policy" toml:"policy"`
	// The StateConfiguration of the SLC used to dictate a State Machine.
	State StateConfiguration `json:"state" yaml:"state" toml:"state" validate:"required"`
	// The Network of the SLC
	Network Network `json:"network,omitempty" yaml:"network,omitempty" toml:"network,omitempty"`
	// Status of the SLC. Typically used by the runtime operating the SLC.
	Status Status `json:"status,omitempty" yaml:"status,omitempty" toml:"status,omitempty"`
}

Contract is the definition of for a Decombine SLC.

func GetFSContract

func GetFSContract(path string) (*Contract, error)

func GetGitHubContract

func GetGitHubContract(token, uri, branch, path string) (*Contract, error)

GetGitHubContract retrieves a Contract from a remote GitHub repository. A Personal Access Token (PAT) token may be provided for private repositories.

func New

func New() Contract

func ValidateJSONPayload

func ValidateJSONPayload(in []byte) (*Contract, error)

ValidateJSONPayload validates a JSON payload input against the Contract struct.

func ValidateTOMLPayload

func ValidateTOMLPayload(in []byte) (*Contract, error)

ValidateTOMLPayload validates a TOML payload input against the Contract struct.

func ValidateYAMLPayload

func ValidateYAMLPayload(in []byte) (*Contract, error)

ValidateYAMLPayload validates a YAML payload input against the Contract struct.

func (*Contract) Connect

func (*Contract) CreateEvent

func (c *Contract) CreateEvent(eventType, source string) (cloudevents.Event, error)

CreateEvent creates a new Event with the given type.

func (*Contract) GetEvents

func (c *Contract) GetEvents() []string

GetEvents returns a list of all events that the Contract StateConfiguration has registered.

func (*Contract) GetState

func (c *Contract) GetState(name string) (State, error)

func (*Contract) InsertState

func (c *Contract) InsertState(s State)

func (*Contract) IsEventRegistered

func (c *Contract) IsEventRegistered(event cloudevents.Event) bool

IsEventRegistered determines if the Event is registered in a Transition.

type ContractText

type ContractText struct {
	// Text URL of the Smart Legal Contract
	URL string `json:"url" yaml:"url" toml:"url" validate:"required,url"`
}

type FSMOption

type FSMOption func(*FSMOptions)

func WithFSPolicyFiles

func WithFSPolicyFiles(path string) FSMOption

WithFSPolicyFiles is an FSMOption that changes the default behavior of the FSM to use Policy files from the file system instead of a remote Git repository. This is useful for testing and development. The path argument is relative to the current working directory.

func WithGitHubToken

func WithGitHubToken(token string) FSMOption

WithGitHubToken is an FSMOption that changes the default behavior of the FSM to use a GitHub Personal Access Token when retrieving Policy files from a remote Git repository.

type FSMOptions

type FSMOptions struct {
	GitHubPAT      string
	FilesystemPath string
}

FSMOptions is a struct that holds options for configuring the behavior of the FSM.

type GitSource

type GitSource struct {
	// The type of the source
	Type string `json:"type,omitempty" yaml:"type,omitempty" toml:"type,omitempty"`
	// The URL of the Git repository
	URL string `json:"url" yaml:"url" toml:"url" validate:"required,url"`
	// The branch of the Git repository
	Branch string `json:"branch" yaml:"branch" toml:"branch"`
	// The path to the Smart Legal Contract Definition file
	Path string `json:"path" yaml:"path" toml:"path"`
}

A GitSource is a Git repository source for Smart Legal Contracts.

type KubernetesAction

type KubernetesAction struct {
	Name              string                         `json:"name,omitempty"`
	Namespace         string                         `json:"namespace,omitempty"`
	KustomizationSpec *kustomizev1.KustomizationSpec `json:"kustomizationSpec,omitempty" yaml:"kustomizationSpec" toml:"kustomizationSpec"`
}

type Network

type Network struct {
	// The Name of the Network. E.g., "decombine"
	Name string `json:"name" yaml:"name" toml:"name" `
	// The API hostname address of the Network. E.g., "api.decombine.com"
	API string `json:"api" yaml:"api" toml:"api" `
	// The URL of the Network for informational purposes. E.g., "https://decombine.com"
	URL string `json:"url" yaml:"url" toml:"url"`
	// EventURL is the URL of the Event Stream.
	EventURL string `json:"eventUrl" yaml:"eventUrl" toml:"eventUrl"`
	// The ClientID of the Network used for OIDC.
	ClientID string `json:"clientId" yaml:"clientId" tom:"clientId" `
	// The Relying Party (RP) Issuer used for OIDC.
	Issuer string `json:"issuer" yaml:"issuer" toml:"issuer"`
	// The DiscoveryEndpoint used for OIDC.
	DiscoveryEndpoint string `json:"discoveryEndpoint" yaml:"discoveryEndpoint" toml:"discoveryEndpoint"`
}

Network provides a reference for remote authentication, authorization, and state management.

type PolicySource

type PolicySource struct {
	// The branch of the Git repository
	Branch string `json:"branch" yaml:"branch" toml:"branch"`
	// The directory containing the OPA policies
	Directory string `json:"directory" yaml:"directory" toml:"directory"`
	// The URL of the Git repository
	URL string `json:"url" yaml:"url" toml:"url" validate:"required,url"`
}

PolicySource for the Open Policy Agent (OPA) policies.

type Reconciler

type Reconciler struct {
	Config       ReconcilerConfig
	EventChannel chan *cloudevents.Event
	Consumer     jetstream.Consumer
	Stream       jetstream.JetStream
	Contract     *Contract
	FSM          *stateless.StateMachine
	Client       client.Client
}

func NewReconciler

func NewReconciler(c *Contract, fsm *stateless.StateMachine, consumer jetstream.Consumer, stream jetstream.JetStream,
	config ReconcilerConfig, options ...ReconcilerOptions) *Reconciler

func (*Reconciler) ConsumeEvent

func (r *Reconciler) ConsumeEvent(ctx context.Context, event *cloudevents.Event, eligible []Transition) error

ConsumeEvent consumes an Event and initiates State Transition if the Event is relevant.

func (*Reconciler) Start

func (r *Reconciler) Start(ctx context.Context) error

type ReconcilerConfig

type ReconcilerConfig struct {
	Workers     int
	MaxMassages int
}

type ReconcilerOptions

type ReconcilerOptions struct {
	// contains filtered or unexported fields
}

func WithKubernetesClient

func WithKubernetesClient(client client.Client) ReconcilerOptions

type State

type State struct {
	// The name of the State
	Name string `json:"name" yaml:"name" toml:"name"`
	// The actions that are executed when the State is entered
	Entry Action `json:"entry" yaml:"entry" toml:"entry"`
	// The actions that are executed when the State is exited
	Exit Action `json:"exit" yaml:"exit" toml:"exit"`
	// The variables associated with the State
	Variables map[string]any `json:"variables" yaml:"variables" toml:"variables"`
	// The transitions that are possible from this State
	Transitions []Transition `json:"transitions" yaml:"transitions" toml:"transitions" validate:"required,gte=0,dive"`
}

A State is a condition of being. It represents a snapshot of the current condition of a Smart Legal Contract.

type StateConfiguration

type StateConfiguration struct {
	// The Initial State of the SLC
	Initial string `json:"initial" yaml:"initial" toml:"initial" validate:"required"`
	// The URL of the StateConfiguration
	URL string `json:"url" yaml:"url" toml:"url" validate:"required,url"`
	// The States that comprise the SLC
	States []State `json:"states" yaml:"states" toml:"states" validate:"required,gte=1,dive"`
}

A StateConfiguration is a collection of States that define the State Machine of a Smart Legal Contract.

type Status

type Status struct {
	// The current state of the smart legal contract
	CurrentState string `json:"currentState,omitempty" yaml:"currentState,omitempty" toml:"currentState,omitempty"`
	// The source state of the smart legal contract
	SourceState string `json:"sourceState,omitempty" yaml:"sourceState,omitempty" toml:"sourceState,omitempty"`
	// The policy state of the smart legal contract
	PolicyState string `json:"policyState,omitempty" yaml:"policyState,omitempty" toml:"policyState,omitempty"`
	// The workload state of the smart legal contract
	WorkloadState string `json:"workloadState,omitempty" yaml:"workloadState,omitempty" toml:"workloadState,omitempty"`
}

type Transition

type Transition struct {
	// The Name of the Transition
	Name string `json:"name" yaml:"name" toml:"name" validate:"required"`
	// The State To which the Transition leads
	To string `json:"to" yaml:"to" toml:"to" validate:"required"`
	// The Event that Triggers the Transition
	On string `json:"on" yaml:"on" toml:"on" validate:"required"`
	// The Guard Conditions that must be satisfied for the Transition to occur
	Conditions []Condition `json:"conditions" yaml:"conditions" toml:"conditions"`
}

Transition is a change from one State to another.

type TransitionCtx

type TransitionCtx struct {
	Input interface{} `json:"input" yaml:"input" toml:"input"`
}

TransitionCtx is used to pass input data to FSM Guard Functions for State Transition evaluation using Open Policy Agent (OPA) Rego policies.

func FromContext

func FromContext(ctx context.Context) (*TransitionCtx, bool)

FromContext returns the transition value stored in ctx, if any.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL