models

package
v0.6.1 Latest Latest
Warning

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

Go to latest
Published: Jun 26, 2019 License: MIT Imports: 35 Imported by: 32

Documentation

Overview

Package models contain the key job components used by the Chainlink application.

Common

Common contains types and functions that are useful across the application. Particularly dealing with the URL field, dates, and time.

Eth

Eth creates transactions and tracks transaction attempts on the Ethereum blockchain.

JobSpec

A JobSpec is the largest unit of work that a Chainlink node can take on. It will have Initiators, which is how a JobRun is started from the job definition, and Tasks, which are the specific instructions for what work needs to be performed. The BridgeType is also located here, and is used to define the location (URL) of external adapters.

ORM

The ORM is the wrapper around the database. It gives a limited set of functions to allow for safe storing and withdrawing of information.

Run

A Run is the actual invocation of work being done on the Job and Task. This comprises of JobRuns and TaskRuns. A JobRun is like a workflow where the steps are the TaskRuns.

i.e. We have a Scheduler Initiator that creates a JobRun every monday based on a JobDefinition. And in turn, those JobRuns have TaskRuns based on the JobDefinition's TaskDefinitions.

Index

Constants

View Source
const (
	// BulkTaskStatusInProgress is the default state of any run status.
	BulkTaskStatusInProgress = BulkTaskStatus("")
	// BulkTaskStatusErrored means a bulk task stopped because it encountered an error.
	BulkTaskStatusErrored = BulkTaskStatus("errored")
	// BulkTaskStatusCompleted means a bulk task finished.
	BulkTaskStatusCompleted = BulkTaskStatus("completed")
)
View Source
const (
	// RunStatusUnstarted is the default state of any run status.
	RunStatusUnstarted = RunStatus("")
	// RunStatusInProgress is used for when a run is actively being executed.
	RunStatusInProgress = RunStatus("in_progress")
	// RunStatusPendingConfirmations is used for when a run is awaiting for block confirmations.
	RunStatusPendingConfirmations = RunStatus("pending_confirmations")
	// RunStatusPendingConnection states that the run is waiting on a connection to the block chain.
	RunStatusPendingConnection = RunStatus("pending_connection")
	// RunStatusPendingBridge is used for when a run is waiting on the completion
	// of another event.
	RunStatusPendingBridge = RunStatus("pending_bridge")
	// RunStatusPendingSleep is used for when a run is waiting on a sleep function to finish.
	RunStatusPendingSleep = RunStatus("pending_sleep")
	// RunStatusErrored is used for when a run has errored and will not complete.
	RunStatusErrored = RunStatus("errored")
	// RunStatusCompleted is used for when a run has successfully completed execution.
	RunStatusCompleted = RunStatus("completed")
)
View Source
const (
	// InitiatorRunLog for tasks in a job to watch an ethereum address
	// and expect a JSON payload from a log event.
	InitiatorRunLog = "runlog"
	// InitiatorCron for tasks in a job to be ran on a schedule.
	InitiatorCron = "cron"
	// InitiatorEthLog for tasks in a job to use the Ethereum blockchain.
	InitiatorEthLog = "ethlog"
	// InitiatorRunAt for tasks in a job to be ran once.
	InitiatorRunAt = "runat"
	// InitiatorWeb for tasks in a job making a web request.
	InitiatorWeb = "web"
	// InitiatorServiceAgreementExecutionLog for tasks in a job to watch a
	// Solidity Coordinator contract and expect a payload from a log event.
	InitiatorServiceAgreementExecutionLog = "execagreement"
)

Types of Initiators (see Initiator struct just below.)

View Source
const (
	RequestLogTopicSignature = iota
	RequestLogTopicJobID
	RequestLogTopicRequester
	RequestLogTopicPayment
)

Descriptive indices of a RunLog's Topic array

View Source
const FunctionSelectorLength = 4

FunctionSelectorLength should always be a length of 4 as a byte.

View Source
const (
	// SignatureLength is the length of the signature in bytes: v = 1, r = 32, s
	// = 32; v + r + s = 65
	SignatureLength = 65
)

Variables

View Source
var (
	// RunLogTopic0original was the original topic to filter for Oracle.sol RunRequest events.
	RunLogTopic0original = utils.MustHash("RunRequest(bytes32,address,uint256,uint256,uint256,bytes)")
	// RunLogTopic20190123withFullfillmentParams was the new RunRequest filter topic as of 2019-01-23,
	// when callback address, callback function, and expiration were added to the data payload.
	RunLogTopic20190123withFullfillmentParams = utils.MustHash("RunRequest(bytes32,address,uint256,uint256,uint256,address,bytes4,uint256,bytes)")
	// RunLogTopic20190207withoutIndexes was the new RunRequest filter topic as of 2019-01-28,
	// after renaming Solidity variables, moving data version, and removing the cast of requestId to uint256
	RunLogTopic20190207withoutIndexes = utils.MustHash("OracleRequest(bytes32,address,bytes32,uint256,address,bytes4,uint256,uint256,bytes)")
	// ServiceAgreementExecutionLogTopic is the signature for the
	// Coordinator.RunRequest(...) events which Chainlink nodes watch for. See
	// https://github.com/smartcontractkit/chainlink/blob/master/evm/contracts/Coordinator.sol#RunRequest
	ServiceAgreementExecutionLogTopic = utils.MustHash("ServiceAgreementExecution(bytes32,address,uint256,uint256,uint256,bytes)")
	// ChainlinkFulfilled is the signature for the event emitted after calling
	// ChainlinkClient.validateChainlinkCallback(requestId).
	// https://github.com/smartcontractkit/chainlink/blob/master/evm/contracts/ChainlinkClient.sol
	ChainlinkFulfilledTopic = utils.MustHash("ChainlinkFulfilled(bytes32)")
	// OracleFullfillmentFunctionID0original is the original function selector for fulfilling Ethereum requests.
	OracleFullfillmentFunctionID0original = utils.MustHash("fulfillData(uint256,bytes32)").Hex()[:10]
	// OracleFulfillmentFunctionID20190123withFulfillmentParams is the function selector for fulfilling Ethereum requests,
	// as updated on 2019-01-23, accepting all fulfillment callback parameters.
	OracleFulfillmentFunctionID20190123withFulfillmentParams = utils.MustHash("fulfillData(uint256,uint256,address,bytes4,uint256,bytes32)").Hex()[:10]
	// OracleFulfillmentFunctionID20190128withoutCast is the function selector for fulfilling Ethereum requests,
	// as updated on 2019-01-28, removing the cast to uint256 for the requestId.
	OracleFulfillmentFunctionID20190128withoutCast = utils.MustHash("fulfillOracleRequest(bytes32,uint256,address,bytes4,uint256,bytes32)").Hex()[:10]
)
View Source
var (
	// ErrorCannotMergeNonObject is returned if a Merge was attempted on a string
	// or array JSON value
	ErrorCannotMergeNonObject = errors.New("Cannot merge, expected object '{}'")
)

Functions

func AuthenticateBridgeType

func AuthenticateBridgeType(bt *BridgeType, token string) (bool, error)

AuthenticateBridgeType returns true if the passed token matches its IncomingToken, or returns false with an error.

func AuthenticateExternalInitiator

func AuthenticateExternalInitiator(eia *ExternalInitiatorAuthentication, ea *ExternalInitiator) (bool, error)

AuthenticateExternalInitiator compares an auth against an initiator and returns true if the password hashes match

func FilterQueryFactory

func FilterQueryFactory(i Initiator, from *big.Int) (ethereum.FilterQuery, error)

FilterQueryFactory returns the ethereum FilterQuery for this initiator.

func HashedSecret

func HashedSecret(eia *ExternalInitiatorAuthentication, salt string) (string, error)

HashedSecret generates a hashed password for an external initiator authentication

func NewBridgeType

NewBridgeType returns a bridge bridge type authentication (with plaintext password) and a bridge type (with hashed password, for persisting)

func NewDatabaseAccessError

func NewDatabaseAccessError(msg string) error

NewDatabaseAccessError returns a database access error.

func NewSecret

func NewSecret() string

NewSecret returns a new secret for use for authenticating external initiators

func NewValidationError

func NewValidationError(msg string, values ...interface{}) error

NewValidationError returns a validation error.

func TopicFiltersForRunLog

func TopicFiltersForRunLog(logTopics []common.Hash, jobID string) ([][]common.Hash, error)

TopicFiltersForRunLog generates the two variations of RunLog IDs that could possibly be entered on a RunLog or a ServiceAgreementExecutionLog. There is the ID, hex encoded and the ID zero padded.

func ValidateBulkDeleteRunRequest

func ValidateBulkDeleteRunRequest(request *BulkDeleteRunRequest) error

ValidateBulkDeleteRunRequest returns a task from a request to make a task

Types

type AddressCollection

type AddressCollection []common.Address

AddressCollection is an array of common.Address serializable to and from a database.

func (*AddressCollection) Scan

func (r *AddressCollection) Scan(value interface{}) error

Scan parses the database value as a string.

func (AddressCollection) ToStrings

func (r AddressCollection) ToStrings() []string

ToStrings returns this address collection as an array of strings.

func (AddressCollection) Value

func (r AddressCollection) Value() (driver.Value, error)

Value returns the string value to be written to the database.

type AnyTime

type AnyTime struct {
	time.Time
	Valid bool
}

AnyTime holds a common field for time, and serializes it as a json number.

func AnyTimeFromNull

func AnyTimeFromNull(t null.Time) AnyTime

AnyTimeFromNull returns an AnyTime from a null.Time.

func NewAnyTime

func NewAnyTime(t time.Time) AnyTime

NewAnyTime creates a new Time.

func (AnyTime) MarshalJSON

func (t AnyTime) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler. It will encode null if this time is null.

func (AnyTime) MarshalText

func (t AnyTime) MarshalText() ([]byte, error)

MarshalText returns null if not set, or the time.

func (*AnyTime) Scan

func (t *AnyTime) Scan(value interface{}) error

Scan reads the database value and returns an instance.

func (*AnyTime) UnmarshalJSON

func (t *AnyTime) UnmarshalJSON(b []byte) error

UnmarshalJSON parses the raw time stored in JSON-encoded data and stores it to the Time field.

func (*AnyTime) UnmarshalText

func (t *AnyTime) UnmarshalText(text []byte) error

UnmarshalText parses null or a valid time.

func (AnyTime) Value

func (t AnyTime) Value() (driver.Value, error)

Value returns this instance serialized for database storage.

type Big

type Big big.Int

Big stores large integers and can deserialize a variety of inputs.

func NewBig

func NewBig(i *big.Int) *Big

NewBig constructs a Big from *big.Int.

func (*Big) Hex

func (b *Big) Hex() string

Hex returns the hex encoding of b.

func (*Big) MarshalJSON

func (b *Big) MarshalJSON() ([]byte, error)

MarshalJSON marshals this instance to base 10 number as string.

func (*Big) MarshalText

func (b *Big) MarshalText() ([]byte, error)

MarshalText marshals this instance to base 10 number as string.

func (*Big) Scan

func (b *Big) Scan(value interface{}) error

Scan reads the database value and returns an instance.

func (*Big) String

func (b *Big) String() string

String returns the base 10 encoding of b.

func (*Big) ToInt

func (b *Big) ToInt() *big.Int

ToInt converts b to a big.Int.

func (*Big) UnmarshalJSON

func (b *Big) UnmarshalJSON(input []byte) error

UnmarshalJSON implements encoding.JSONUnmarshaler.

func (*Big) UnmarshalText

func (b *Big) UnmarshalText(input []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

func (Big) Value

func (b Big) Value() (driver.Value, error)

Value returns this instance serialized for database storage.

type BlockHeader

type BlockHeader struct {
	ParentHash  common.Hash      `json:"parentHash"`
	UncleHash   common.Hash      `json:"sha3Uncles"`
	Coinbase    common.Address   `json:"miner"`
	Root        common.Hash      `json:"stateRoot"`
	TxHash      common.Hash      `json:"transactionsRoot"`
	ReceiptHash common.Hash      `json:"receiptsRoot"`
	Bloom       types.Bloom      `json:"logsBloom"`
	Difficulty  hexutil.Big      `json:"difficulty"`
	Number      hexutil.Big      `json:"number"`
	GasLimit    hexutil.Uint64   `json:"gasLimit"`
	GasUsed     hexutil.Uint64   `json:"gasUsed"`
	Time        hexutil.Big      `json:"timestamp"`
	Extra       hexutil.Bytes    `json:"extraData"`
	Nonce       types.BlockNonce `json:"nonce"`
	GethHash    common.Hash      `json:"mixHash"`
	ParityHash  common.Hash      `json:"hash"`
}

BlockHeader represents a block header in the Ethereum blockchain. Deliberately does not have required fields because some fields aren't present depending on the Ethereum node. i.e. Parity does not always send mixHash

func (BlockHeader) Hash

func (h BlockHeader) Hash() common.Hash

Hash will return GethHash if it exists otherwise it returns the ParityHash

func (BlockHeader) ToHead

func (h BlockHeader) ToHead() *Head

ToHead converts a given BlockHeader to a Head instance.

type BridgeRunResult

type BridgeRunResult struct {
	RunResult
	ExternalPending bool   `json:"pending"`
	AccessToken     string `json:"accessToken"`
}

BridgeRunResult handles the parsing of RunResults from external adapters.

func (*BridgeRunResult) UnmarshalJSON

func (brr *BridgeRunResult) UnmarshalJSON(input []byte) error

UnmarshalJSON parses the given input and updates the BridgeRunResult in the external adapter format.

type BridgeType

type BridgeType struct {
	Name                   TaskType     `json:"name" gorm:"primary_key"`
	URL                    WebURL       `json:"url"`
	Confirmations          uint32       `json:"confirmations"`
	IncomingTokenHash      string       `json:"-"`
	Salt                   string       `json:"-"`
	OutgoingToken          string       `json:"outgoingToken"`
	MinimumContractPayment *assets.Link `json:"minimumContractPayment" gorm:"type:varchar(255)"`
}

BridgeType is used for external adapters and has fields for the name of the adapter and its URL.

func (BridgeType) GetID

func (bt BridgeType) GetID() string

GetID returns the ID of this structure for jsonapi serialization.

func (BridgeType) GetName

func (bt BridgeType) GetName() string

GetName returns the pluralized "type" of this structure for jsonapi serialization.

func (*BridgeType) SetID

func (bt *BridgeType) SetID(value string) error

SetID is used to set the ID of this structure when deserializing from jsonapi documents.

type BridgeTypeAuthentication

type BridgeTypeAuthentication struct {
	Name                   TaskType     `json:"name"`
	URL                    WebURL       `json:"url"`
	Confirmations          uint32       `json:"confirmations"`
	IncomingToken          string       `json:"incomingToken"`
	OutgoingToken          string       `json:"outgoingToken"`
	MinimumContractPayment *assets.Link `json:"minimumContractPayment"`
}

BridgeTypeAuthentication is the record returned in response to a request to create a BridgeType

func (BridgeTypeAuthentication) GetID

func (bt BridgeTypeAuthentication) GetID() string

GetID returns the ID of this structure for jsonapi serialization.

func (BridgeTypeAuthentication) GetName

func (bt BridgeTypeAuthentication) GetName() string

GetName returns the pluralized "type" of this structure for jsonapi serialization.

func (*BridgeTypeAuthentication) SetID

func (bt *BridgeTypeAuthentication) SetID(value string) error

SetID is used to set the ID of this structure when deserializing from jsonapi documents.

type BridgeTypeRequest

type BridgeTypeRequest struct {
	Name                   TaskType     `json:"name"`
	URL                    WebURL       `json:"url"`
	Confirmations          uint32       `json:"confirmations"`
	MinimumContractPayment *assets.Link `json:"minimumContractPayment"`
}

BridgeTypeRequest is the incoming record used to create a BridgeType

func (BridgeTypeRequest) GetID

func (bt BridgeTypeRequest) GetID() string

GetID returns the ID of this structure for jsonapi serialization.

func (BridgeTypeRequest) GetName

func (bt BridgeTypeRequest) GetName() string

GetName returns the pluralized "type" of this structure for jsonapi serialization.

func (*BridgeTypeRequest) SetID

func (bt *BridgeTypeRequest) SetID(value string) error

SetID is used to set the ID of this structure when deserializing from jsonapi documents.

type BulkDeleteRunRequest

type BulkDeleteRunRequest struct {
	ID            uint                `gorm:"primary_key"`
	Status        RunStatusCollection `json:"status" gorm:"type:text"`
	UpdatedBefore time.Time           `json:"updatedBefore"`
}

BulkDeleteRunRequest describes the query for deletion of runs

type BulkTaskStatus

type BulkTaskStatus string

BulkTaskStatus indicates what a bulk task is doing.

func (*BulkTaskStatus) Scan

func (t *BulkTaskStatus) Scan(value interface{}) error

Scan reads the database value and returns an instance.

func (BulkTaskStatus) Value

func (t BulkTaskStatus) Value() (driver.Value, error)

Value returns this instance serialized for database storage.

type ChangePasswordRequest

type ChangePasswordRequest struct {
	OldPassword string `json:"oldPassword"`
	NewPassword string `json:"newPassword"`
}

ChangePasswordRequest sets a new password for the current Session's User.

type CreateKeyRequest

type CreateKeyRequest struct {
	CurrentPassword string `json:"current_password"`
}

CreateKeyRequest represents a request to add an ethereum key.

type Cron

type Cron string

Cron holds the string that will represent the spec of the cron-job. It uses 6 fields to represent the seconds (1), minutes (2), hours (3), day of the month (4), month (5), and day of the week (6).

func (Cron) String

func (c Cron) String() string

String returns the current Cron spec string.

func (*Cron) UnmarshalJSON

func (c *Cron) UnmarshalJSON(b []byte) error

UnmarshalJSON parses the raw spec stored in JSON-encoded data and stores it to the Cron string.

type DatabaseAccessError

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

DatabaseAccessError is an error that occurs during database access.

func (*DatabaseAccessError) Error

func (e *DatabaseAccessError) Error() string

type EIP55Address

type EIP55Address string

EIP55Address is a newtype for string which persists an ethereum address in its original string representation which includes a leading 0x, and EIP55 checksum which is represented by the case of digits A-F.

func NewEIP55Address

func NewEIP55Address(s string) (EIP55Address, error)

NewEIP55Address creates an EIP55Address from a string, an error is returned if:

1) There is no leading 0x 2) The length is wrong 3) There are any non hexadecimal characters 4) The checksum fails

func (EIP55Address) Address

func (a EIP55Address) Address() common.Address

Address returns EIP55Address as a go-ethereum Address type

func (EIP55Address) Big

func (a EIP55Address) Big() *big.Int

Big returns a big.Int representation

func (EIP55Address) Bytes

func (a EIP55Address) Bytes() []byte

Bytes returns the raw bytes

func (EIP55Address) Format

func (a EIP55Address) Format(s fmt.State, c rune)

Format implements fmt.Formatter

func (EIP55Address) Hash

func (a EIP55Address) Hash() common.Hash

Hash returns the Hash

func (*EIP55Address) Scan

func (a *EIP55Address) Scan(value interface{}) error

Scan reads the database value and returns an instance.

func (EIP55Address) String

func (a EIP55Address) String() string

String implements the stringer interface and is used also by the logger.

func (*EIP55Address) UnmarshalJSON

func (a *EIP55Address) UnmarshalJSON(input []byte) error

UnmarshalJSON parses a hash from a JSON string

func (*EIP55Address) UnmarshalText

func (a *EIP55Address) UnmarshalText(input []byte) error

UnmarshalText parses a hash from plain text

func (EIP55Address) Value

func (a EIP55Address) Value() (driver.Value, error)

Value returns this instance serialized for database storage.

type EIP55AddressCollection

type EIP55AddressCollection []EIP55Address

EIP55AddressCollection is an array of EIP55Addresses.

func (*EIP55AddressCollection) Scan

func (c *EIP55AddressCollection) Scan(value interface{}) error

Scan reads the database value and returns an instance.

func (EIP55AddressCollection) Value

Value returns this instance serialized for database storage.

type Encumbrance

type Encumbrance struct {
	ID         uint                   `json:"-" gorm:"primary_key;auto_increment"`
	Payment    *assets.Link           `json:"payment" gorm:"type:varchar(255)"`
	Expiration uint64                 `json:"expiration"`
	EndAt      AnyTime                `json:"endAt"`
	Oracles    EIP55AddressCollection `json:"oracles" gorm:"type:text"`
}

Encumbrance connects job specifications with on-chain encumbrances.

func (Encumbrance) ABI

func (e Encumbrance) ABI() ([]byte, error)

ABI packs the encumberance as a byte array using the same technique as abi.encodePacked, meaning that addresses are padded with left 0s to match hashes in the oracle list

type EthLogEvent

type EthLogEvent struct {
	InitiatorLogEvent
}

EthLogEvent provides functionality specific to a log event emitted for an eth log initiator.

type EthSubscription

type EthSubscription interface {
	Err() <-chan error
	Unsubscribe()
}

EthSubscription should implement Err() <-chan error and Unsubscribe()

type ExternalInitiator

type ExternalInitiator struct {
	*gorm.Model
	AccessKey    string
	Salt         string
	HashedSecret string
}

ExternalInitiator represents a user that can initiate runs remotely

func NewExternalInitiator

func NewExternalInitiator(eia *ExternalInitiatorAuthentication) (*ExternalInitiator, error)

NewExternalInitiator generates an ExternalInitiator from an ExternalInitiatorAuthentication, hashing the password for storage

type ExternalInitiatorAuthentication

type ExternalInitiatorAuthentication struct {
	AccessKey string
	Secret    string
}

ExternalInitiatorAuthentication represents the credentials needed to authenticate as an external initiator

func NewExternalInitiatorAuthentication

func NewExternalInitiatorAuthentication() *ExternalInitiatorAuthentication

NewExternalInitiatorAuthentication returns a new ExternalInitiatorAuthentication with a freshly generated access key and secret, this is intended to be supplied to the user and saved, as it cannot be regenerated in the future.

func (*ExternalInitiatorAuthentication) GetID

GetID returns the ID of this structure for jsonapi serialization.

func (*ExternalInitiatorAuthentication) GetName

func (eia *ExternalInitiatorAuthentication) GetName() string

GetName returns the pluralized "type" of this structure for jsonapi serialization.

func (*ExternalInitiatorAuthentication) SetID

SetID returns the ID of this structure for jsonapi serialization.

type FunctionSelector

type FunctionSelector [FunctionSelectorLength]byte

FunctionSelector is the first four bytes of the call data for a function call and specifies the function to be called.

func BytesToFunctionSelector

func BytesToFunctionSelector(b []byte) FunctionSelector

BytesToFunctionSelector converts the given bytes to a FunctionSelector.

func HexToFunctionSelector

func HexToFunctionSelector(s string) FunctionSelector

HexToFunctionSelector converts the given string to a FunctionSelector.

func (FunctionSelector) Bytes

func (f FunctionSelector) Bytes() []byte

Bytes returns the FunctionSelector as a byte slice

func (*FunctionSelector) SetBytes

func (f *FunctionSelector) SetBytes(b []byte)

SetBytes sets the FunctionSelector to that of the given bytes (will trim).

func (FunctionSelector) String

func (f FunctionSelector) String() string

String returns the FunctionSelector as a string type.

func (*FunctionSelector) UnmarshalJSON

func (f *FunctionSelector) UnmarshalJSON(input []byte) error

UnmarshalJSON parses the raw FunctionSelector and sets the FunctionSelector type to the given input.

func (FunctionSelector) WithoutPrefix

func (f FunctionSelector) WithoutPrefix() string

WithoutPrefix returns the FunctionSelector as a string without the '0x' prefix.

type Head struct {
	ID     uint64      `gorm:"primary_key;auto_increment"`
	Hash   common.Hash `gorm:"not null"`
	Number int64       `gorm:"index;not null"`
}

Head represents a BlockNumber, BlockHash.

func NewHead

func NewHead(bigint *big.Int, hash common.Hash) *Head

NewHead returns a Head instance with a BlockNumber and BlockHash.

func (*Head) GreaterThan

func (l *Head) GreaterThan(r *Head) bool

GreaterThan compares BlockNumbers and returns true if the reciever BlockNumber is greater than the supplied BlockNumber

func (*Head) NextInt

func (l *Head) NextInt() *big.Int

NextInt returns the next BlockNumber as big.int, or nil if nil to represent latest.

func (*Head) String

func (l *Head) String() string

String returns a string representation of this number.

func (*Head) ToInt

func (l *Head) ToInt() *big.Int

ToInt return the height as a *big.Int. Also handles nil by returning nil.

type Initiator

type Initiator struct {
	ID        uint   `json:"id" gorm:"primary_key;auto_increment"`
	JobSpecID string `json:"jobSpecId" gorm:"index;type:varchar(36) REFERENCES job_specs(id)"`
	// Type is one of the Initiator* string constants defined just above.
	Type            string    `json:"type" gorm:"index;not null"`
	CreatedAt       time.Time `gorm:"index"`
	InitiatorParams `json:"params,omitempty"`
	DeletedAt       null.Time `json:"-" gorm:"index"`
}

Initiator could be thought of as a trigger, defines how a Job can be started, or rather, how a JobRun can be created from a Job. Initiators will have their own unique ID, but will be associated to a parent JobID.

func (Initiator) IsLogInitiated

func (i Initiator) IsLogInitiated() bool

IsLogInitiated Returns true if triggered by event logs.

func (*Initiator) UnmarshalJSON

func (i *Initiator) UnmarshalJSON(input []byte) error

UnmarshalJSON parses the raw initiator data and updates the initiator as long as the type is valid.

type InitiatorLogEvent

type InitiatorLogEvent struct {
	Log       Log
	JobSpec   JobSpec
	Initiator Initiator
}

InitiatorLogEvent encapsulates all information as a result of a received log from an InitiatorSubscription.

func (InitiatorLogEvent) BlockNumber

func (le InitiatorLogEvent) BlockNumber() *big.Int

BlockNumber returns the block number for the given InitiatorSubscriptionLogEvent.

func (InitiatorLogEvent) ContractPayment

func (le InitiatorLogEvent) ContractPayment() (*assets.Link, error)

ContractPayment returns the amount attached to a contract to pay the Oracle upon fulfillment.

func (InitiatorLogEvent) ForLogger

func (le InitiatorLogEvent) ForLogger(kvs ...interface{}) []interface{}

ForLogger formats the InitiatorSubscriptionLogEvent for easy common formatting in logs (trace statements, not ethereum events).

func (InitiatorLogEvent) GetInitiator

func (le InitiatorLogEvent) GetInitiator() Initiator

GetInitiator returns the initiator.

func (InitiatorLogEvent) GetJobSpec

func (le InitiatorLogEvent) GetJobSpec() JobSpec

GetJobSpec returns the associated JobSpec

func (InitiatorLogEvent) GetLog

func (le InitiatorLogEvent) GetLog() Log

GetLog returns the log.

func (InitiatorLogEvent) JSON

func (le InitiatorLogEvent) JSON() (JSON, error)

JSON returns the eth log as JSON.

func (InitiatorLogEvent) LogRequest

func (le InitiatorLogEvent) LogRequest() LogRequest

LogRequest is a factory method that coerces this log event to the correct type based on Initiator.Type, exposed by the LogRequest interface.

func (InitiatorLogEvent) RunRequest

func (le InitiatorLogEvent) RunRequest() (RunRequest, error)

RunRequest returns a run request instance with the transaction hash, present on all log initiated runs.

func (InitiatorLogEvent) ToDebug

func (le InitiatorLogEvent) ToDebug()

ToDebug prints this event via logger.Debug.

func (InitiatorLogEvent) Validate

func (le InitiatorLogEvent) Validate() bool

Validate returns true, no validation on this log event type.

func (InitiatorLogEvent) ValidateRequester

func (le InitiatorLogEvent) ValidateRequester() error

ValidateRequester returns true since all requests are valid for base initiator log events.

type InitiatorParams

type InitiatorParams struct {
	Schedule   Cron              `json:"schedule,omitempty"`
	Time       AnyTime           `json:"time,omitempty"`
	Ran        bool              `json:"ran,omitempty"`
	Address    common.Address    `json:"address,omitempty" gorm:"index"`
	Requesters AddressCollection `json:"requesters,omitempty" gorm:"type:text"`
}

InitiatorParams is a collection of the possible parameters that different Initiators may require.

type InitiatorRequest

type InitiatorRequest struct {
	Type            string `json:"type"`
	InitiatorParams `json:"params,omitempty"`
}

InitiatorRequest represents a schema for incoming initiator requests as used by the API.

type JSON

type JSON struct {
	gjson.Result
}

JSON stores the json types string, number, bool, and null. Arrays and Objects are returned as their raw json types.

func ParseCBOR

func ParseCBOR(b []byte) (JSON, error)

ParseCBOR attempts to coerce the input byte array into valid CBOR and then coerces it into a JSON object.

func ParseJSON

func ParseJSON(b []byte) (JSON, error)

ParseJSON attempts to coerce the input byte array into valid JSON and parse it into a JSON object.

func ParseRunLog

func ParseRunLog(log Log) (JSON, error)

ParseRunLog decodes the CBOR in the ABI of the log event.

func (JSON) Add

func (j JSON) Add(key string, val interface{}) (JSON, error)

Add returns a new instance of JSON with the new value added.

func (JSON) Bytes

func (j JSON) Bytes() []byte

Bytes returns the raw JSON.

func (JSON) CBOR

func (j JSON) CBOR() ([]byte, error)

CBOR returns a bytes array of the JSON map or array encoded to CBOR.

func (JSON) Delete

func (j JSON) Delete(key string) (JSON, error)

Delete returns a new instance of JSON with the specified key removed.

func (JSON) Empty

func (j JSON) Empty() bool

Empty returns true if the JSON does not exist.

func (JSON) MarshalJSON

func (j JSON) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON data if it already exists, returns an empty JSON object as bytes if not.

func (JSON) Merge

func (j JSON) Merge(j2 JSON) (JSON, error)

Merge combines the given JSON with the existing JSON.

func (*JSON) Scan

func (j *JSON) Scan(value interface{}) error

Scan reads the database value and returns an instance.

func (*JSON) UnmarshalJSON

func (j *JSON) UnmarshalJSON(b []byte) error

UnmarshalJSON parses the JSON bytes and stores in the *JSON pointer.

func (JSON) Value

func (j JSON) Value() (driver.Value, error)

Value returns this instance serialized for database storage.

type JSONAPIError

type JSONAPIError struct {
	Detail string `json:"detail"`
}

JSONAPIError is an individual JSONAPI Error.

type JSONAPIErrors

type JSONAPIErrors struct {
	Errors []JSONAPIError `json:"errors"`
}

JSONAPIErrors holds errors conforming to the JSONAPI spec.

func NewJSONAPIErrors

func NewJSONAPIErrors() *JSONAPIErrors

NewJSONAPIErrors creates an instance of JSONAPIErrors, with the intention of managing a collection of them.

func NewJSONAPIErrorsWith

func NewJSONAPIErrorsWith(detail string) *JSONAPIErrors

NewJSONAPIErrorsWith creates an instance of JSONAPIErrors populated with this single detail.

func (*JSONAPIErrors) Add

func (jae *JSONAPIErrors) Add(detail string)

Add adds a new error to JSONAPIErrors with the passed detail.

func (*JSONAPIErrors) CoerceEmptyToNil

func (jae *JSONAPIErrors) CoerceEmptyToNil() error

CoerceEmptyToNil will return nil if JSONAPIErrors has no errors.

func (*JSONAPIErrors) Error

func (jae *JSONAPIErrors) Error() string

Error collapses the collection of errors into a collection of comma separated strings.

func (*JSONAPIErrors) Merge

func (jae *JSONAPIErrors) Merge(e error)

Merge combines the arrays of the passed error if it is of type JSONAPIErrors, otherwise simply adds a single error with the error string as detail.

type JobRun

type JobRun struct {
	ID             string     `json:"id" gorm:"primary_key;not null"`
	JobSpecID      string     `json:"jobId" gorm:"index;not null;type:varchar(36) REFERENCES job_specs(id)"`
	Result         RunResult  `json:"result"`
	ResultID       uint       `json:"-"`
	RunRequest     RunRequest `json:"-"`
	RunRequestID   uint       `json:"-"`
	Status         RunStatus  `json:"status" gorm:"index"`
	TaskRuns       []TaskRun  `json:"taskRuns"`
	CreatedAt      time.Time  `json:"createdAt" gorm:"index"`
	FinishedAt     null.Time  `json:"finishedAt"`
	UpdatedAt      time.Time  `json:"updatedAt"`
	Initiator      Initiator  `json:"initiator" gorm:"association_autoupdate:false;association_autocreate:false"`
	InitiatorID    uint       `json:"-"`
	CreationHeight *Big       `json:"creationHeight" gorm:"type:varchar(255)"`
	ObservedHeight *Big       `json:"observedHeight" gorm:"type:varchar(255)"`
	Overrides      RunResult  `json:"overrides"`
	OverridesID    uint       `json:"-"`
	DeletedAt      null.Time  `json:"-" gorm:"index"`
}

JobRun tracks the status of a job by holding its TaskRuns and the Result of each Run.

func JobRunsWithStatus

func JobRunsWithStatus(runs []JobRun, status RunStatus) []JobRun

JobRunsWithStatus filters passed job runs returning those that have the desired status, entirely in memory.

func (*JobRun) ApplyResult

func (jr *JobRun) ApplyResult(result RunResult)

ApplyResult updates the JobRun's Result and Status

func (JobRun) ForLogger

func (jr JobRun) ForLogger(kvs ...interface{}) []interface{}

ForLogger formats the JobRun for a common formatting in the log.

func (JobRun) GetID

func (jr JobRun) GetID() string

GetID returns the ID of this structure for jsonapi serialization.

func (JobRun) GetName

func (jr JobRun) GetName() string

GetName returns the pluralized "type" of this structure for jsonapi serialization.

func (*JobRun) NextTaskRun

func (jr *JobRun) NextTaskRun() *TaskRun

NextTaskRun returns the next immediate TaskRun in the list of unfinished TaskRuns.

func (*JobRun) NextTaskRunIndex

func (jr *JobRun) NextTaskRunIndex() (int, bool)

NextTaskRunIndex returns the position of the next unfinished task

func (*JobRun) PreviousTaskRun

func (jr *JobRun) PreviousTaskRun() *TaskRun

PreviousTaskRun returns the last task to be processed, if it exists

func (*JobRun) SetError

func (jr *JobRun) SetError(err error)

SetError sets this job run to failed and saves the error message

func (*JobRun) SetFinishedAt

func (jr *JobRun) SetFinishedAt()

SetFinishedAt sets the JobRun's finished at time to now.

func (*JobRun) SetID

func (jr *JobRun) SetID(value string) error

SetID is used to set the ID of this structure when deserializing from jsonapi documents.

func (*JobRun) TasksRemain

func (jr *JobRun) TasksRemain() bool

TasksRemain returns true if there are unfinished tasks left for this job run

type JobSpec

type JobSpec struct {
	ID         string      `json:"id,omitempty" gorm:"primary_key;not null"`
	CreatedAt  time.Time   `json:"createdAt" gorm:"index"`
	Initiators []Initiator `json:"initiators"`
	Tasks      []TaskSpec  `json:"tasks"`
	StartAt    null.Time   `json:"startAt" gorm:"index"`
	EndAt      null.Time   `json:"endAt" gorm:"index"`
	DeletedAt  null.Time   `json:"-" gorm:"index"`
}

JobSpec is the definition for all the work to be carried out by the node for a given contract. It contains the Initiators, Tasks (which are the individual steps to be carried out), StartAt, EndAt, and CreatedAt fields.

func NewJob

func NewJob() JobSpec

NewJob initializes a new job by generating a unique ID and setting the CreatedAt field to the time of invokation.

func NewJobFromRequest

func NewJobFromRequest(jsr JobSpecRequest) JobSpec

NewJobFromRequest creates a JobSpec from the corresponding parameters in a JobSpecRequest

func (JobSpec) Ended

func (j JobSpec) Ended(t time.Time) bool

Ended returns true if the job has ended.

func (JobSpec) GetID

func (j JobSpec) GetID() string

GetID returns the ID of this structure for jsonapi serialization.

func (JobSpec) GetName

func (j JobSpec) GetName() string

GetName returns the pluralized "type" of this structure for jsonapi serialization.

func (JobSpec) InitiatorsFor

func (j JobSpec) InitiatorsFor(types ...string) []Initiator

InitiatorsFor returns an array of Initiators for the given list of Initiator types.

func (JobSpec) IsLogInitiated

func (j JobSpec) IsLogInitiated() bool

IsLogInitiated Returns true if any of the job's initiators are triggered by event logs.

func (JobSpec) NewRun

func (j JobSpec) NewRun(i Initiator) JobRun

NewRun initializes the job by creating the IDs for the job and all associated tasks, and setting the CreatedAt field.

func (*JobSpec) SetID

func (j *JobSpec) SetID(value string) error

SetID is used to set the ID of this structure when deserializing from jsonapi documents.

func (JobSpec) Started

func (j JobSpec) Started(t time.Time) bool

Started returns true if the job has started.

func (JobSpec) WebAuthorized

func (j JobSpec) WebAuthorized() bool

WebAuthorized returns true if the "web" initiator is present.

type JobSpecRequest

type JobSpecRequest struct {
	Initiators []InitiatorRequest `json:"initiators"`
	Tasks      []TaskSpecRequest  `json:"tasks"`
	StartAt    null.Time          `json:"startAt"`
	EndAt      null.Time          `json:"endAt"`
}

JobSpecRequest represents a schema for the incoming job spec request as used by the API.

type Key

type Key struct {
	Address EIP55Address `gorm:"primary_key;type:varchar(64)"`
	JSON    JSON         `gorm:"type:text"`
}

Key holds the private key metadata for a given address that is used to unlock said key when given a password.

func NewKeyFromFile

func NewKeyFromFile(path string) (*Key, error)

NewKeyFromFile creates an instance in memory from a key file on disk.

func (*Key) WriteToDisk

func (k *Key) WriteToDisk(path string) error

WriteToDisk writes this key to disk at the passed path.

type Log

type Log struct {
	// Consensus fields:
	// address of the contract that generated the event
	Address common.Address `json:"address" gencodec:"required"`
	// list of topics provided by the contract.
	Topics []common.Hash `json:"topics" gencodec:"required"`
	// supplied by the contract, usually ABI-encoded
	Data []byte `json:"data" gencodec:"required"`

	// Derived fields. These fields are filled in by the node
	// but not secured by consensus.
	// block in which the transaction was included
	BlockNumber uint64 `json:"blockNumber"`
	// hash of the transaction
	TxHash common.Hash `json:"transactionHash"`
	// index of the transaction in the block
	TxIndex uint `json:"transactionIndex"`
	// hash of the block in which the transaction was included
	BlockHash common.Hash `json:"blockHash"`
	// index of the log in the receipt
	Index uint `json:"logIndex"`

	// The Removed field is true if this log was reverted due to a chain reorganisation.
	// You must pay attention to this field if you receive logs through a filter query.
	Removed bool `json:"removed"`
}

Log represents a contract log event. These events are generated by the LOG opcode and stored/indexed by the node.

func (Log) MarshalJSON

func (l Log) MarshalJSON() ([]byte, error)

MarshalJSON marshals as JSON.

func (*Log) UnmarshalJSON

func (l *Log) UnmarshalJSON(input []byte) error

UnmarshalJSON unmarshals from JSON.

type LogRequest

type LogRequest interface {
	GetLog() Log
	GetJobSpec() JobSpec
	GetInitiator() Initiator

	Validate() bool
	JSON() (JSON, error)
	ToDebug()
	ForLogger(kvs ...interface{}) []interface{}
	ContractPayment() (*assets.Link, error)
	ValidateRequester() error
	BlockNumber() *big.Int
	RunRequest() (RunRequest, error)
}

LogRequest is the interface to allow polymorphic functionality of different types of LogEvents. i.e. EthLogEvent, RunLogEvent, ServiceAgreementLogEvent, OracleLogEvent

type RunLogEvent

type RunLogEvent struct {
	InitiatorLogEvent
}

RunLogEvent provides functionality specific to a log event emitted for a run log initiator.

func (RunLogEvent) ContractPayment

func (le RunLogEvent) ContractPayment() (*assets.Link, error)

ContractPayment returns the amount attached to a contract to pay the Oracle upon fulfillment.

func (RunLogEvent) JSON

func (le RunLogEvent) JSON() (JSON, error)

JSON decodes the RunLogEvent's data converts it to a JSON object.

func (RunLogEvent) Requester

func (le RunLogEvent) Requester() common.Address

Requester pulls the requesting address out of the LogEvent's topics.

func (RunLogEvent) RunRequest

func (le RunLogEvent) RunRequest() (RunRequest, error)

RunRequest returns an RunRequest instance with all parameters from a run log topic, like RequestID.

func (RunLogEvent) Validate

func (le RunLogEvent) Validate() bool

Validate returns whether or not the contained log has a properly encoded job id.

func (RunLogEvent) ValidateRequester

func (le RunLogEvent) ValidateRequester() error

ValidateRequester returns true if the requester matches the one associated with the initiator.

type RunRequest

type RunRequest struct {
	ID        uint `gorm:"primary_key"`
	RequestID *string
	TxHash    *common.Hash
	Requester *common.Address
	CreatedAt time.Time
}

RunRequest stores the fields used to initiate the parent job run.

func NewRunRequest

func NewRunRequest() RunRequest

NewRunRequest returns a new RunRequest instance.

type RunResult

type RunResult struct {
	ID              uint         `json:"-" gorm:"primary_key;auto_increment"`
	CachedJobRunID  string       `json:"jobRunId"`
	CachedTaskRunID string       `json:"taskRunId"`
	Data            JSON         `json:"data" gorm:"type:text"`
	Status          RunStatus    `json:"status"`
	ErrorMessage    null.String  `json:"error"`
	Amount          *assets.Link `json:"amount,omitempty" gorm:"type:varchar(255)"`
}

RunResult keeps track of the outcome of a TaskRun or JobRun. It stores the Data and ErrorMessage, and contains a field to track the status.

func (*RunResult) Add

func (rr *RunResult) Add(key string, result interface{})

Add adds a key and result to the RunResult's JSON payload.

func (*RunResult) ApplyResult

func (rr *RunResult) ApplyResult(val interface{})

ApplyResult saves a value to a RunResult with the key result.

func (*RunResult) CompleteWithResult

func (rr *RunResult) CompleteWithResult(val interface{})

CompleteWithResult saves a value to a RunResult and marks it as completed

func (*RunResult) Error

func (rr *RunResult) Error() string

Error returns the string value of the ErrorMessage field.

func (*RunResult) Get

func (rr *RunResult) Get(path string) gjson.Result

Get searches for and returns the JSON at the given path.

func (*RunResult) GetError

func (rr *RunResult) GetError() error

GetError returns the error of a RunResult if it is present.

func (*RunResult) HasError

func (rr *RunResult) HasError() bool

HasError returns true if the ErrorMessage is present.

func (*RunResult) MarkPendingBridge

func (rr *RunResult) MarkPendingBridge()

MarkPendingBridge sets the status to pending_bridge

func (*RunResult) MarkPendingConfirmations

func (rr *RunResult) MarkPendingConfirmations()

MarkPendingConfirmations sets the status to pending_confirmations.

func (*RunResult) MarkPendingConnection

func (rr *RunResult) MarkPendingConnection()

MarkPendingConnection sets the status to pending_connection.

func (*RunResult) Merge

func (rr *RunResult) Merge(in RunResult) error

Merge saves the specified result's data onto the receiving RunResult. The input result's data takes preference over the receivers'.

func (*RunResult) Result

func (rr *RunResult) Result() gjson.Result

Result returns the result as a gjson object

func (*RunResult) ResultString

func (rr *RunResult) ResultString() (string, error)

ResultString returns the string result of the Data JSON field.

func (*RunResult) SetError

func (rr *RunResult) SetError(err error)

SetError marks the result as errored and saves the specified error message

type RunStatus

type RunStatus string

RunStatus is a string that represents the run status

func (RunStatus) CanStart

func (s RunStatus) CanStart() bool

CanStart returns true if the run is ready to begin processed.

func (RunStatus) Completed

func (s RunStatus) Completed() bool

Completed returns true if the status is RunStatusCompleted.

func (RunStatus) Errored

func (s RunStatus) Errored() bool

Errored returns true if the status is RunStatusErrored.

func (RunStatus) Finished

func (s RunStatus) Finished() bool

Finished returns true if the status is final and can't be changed.

func (RunStatus) Pending

func (s RunStatus) Pending() bool

Pending returns true if the status is pending external or confirmations.

func (RunStatus) PendingBridge

func (s RunStatus) PendingBridge() bool

PendingBridge returns true if the status is pending_bridge.

func (RunStatus) PendingConfirmations

func (s RunStatus) PendingConfirmations() bool

PendingConfirmations returns true if the status is pending_confirmations.

func (RunStatus) PendingConnection

func (s RunStatus) PendingConnection() bool

PendingConnection returns true if the status is pending_connection.

func (RunStatus) PendingSleep

func (s RunStatus) PendingSleep() bool

PendingSleep returns true if the status is pending_sleep.

func (RunStatus) Runnable

func (s RunStatus) Runnable() bool

Runnable returns true if the status is ready to be run.

func (*RunStatus) Scan

func (s *RunStatus) Scan(value interface{}) error

Scan reads the database value and returns an instance.

func (RunStatus) Unstarted

func (s RunStatus) Unstarted() bool

Unstarted returns true if the status is the initial state.

func (RunStatus) Value

func (s RunStatus) Value() (driver.Value, error)

Value returns this instance serialized for database storage.

type RunStatusCollection

type RunStatusCollection []RunStatus

RunStatusCollection is an array of RunStatus.

func (*RunStatusCollection) Scan

func (r *RunStatusCollection) Scan(value interface{}) error

Scan reads the database value and returns an instance.

func (RunStatusCollection) ToStrings

func (r RunStatusCollection) ToStrings() []string

ToStrings returns a copy of RunStatusCollection as an array of strings.

func (RunStatusCollection) Value

func (r RunStatusCollection) Value() (driver.Value, error)

Value returns this instance serialized for database storage.

type SendEtherRequest

type SendEtherRequest struct {
	DestinationAddress common.Address `json:"address"`
	FromAddress        common.Address `json:"from"`
	Amount             *assets.Eth    `json:"amount"`
}

SendEtherRequest represents a request to transfer ETH.

type ServiceAgreement

type ServiceAgreement struct {
	ID            string      `json:"id" gorm:"primary_key"`
	CreatedAt     time.Time   `json:"createdAt" gorm:"index"`
	Encumbrance   Encumbrance `json:"encumbrance"`
	EncumbranceID uint        `json:"-"`
	RequestBody   string      `json:"requestBody"`
	Signature     Signature   `json:"signature" gorm:"type:varchar(255)"`
	JobSpec       JobSpec     `gorm:"foreignkey:JobSpecID"`
	JobSpecID     string      `json:"jobSpecId" gorm:"index;not null;type:varchar(36) REFERENCES job_specs(id)"`
}

ServiceAgreement connects job specifications with on-chain encumbrances.

func BuildServiceAgreement

func BuildServiceAgreement(us UnsignedServiceAgreement, signer Signer) (ServiceAgreement, error)

BuildServiceAgreement builds a signed service agreement

func (ServiceAgreement) GetID

func (sa ServiceAgreement) GetID() string

GetID returns the ID of this structure for jsonapi serialization.

func (ServiceAgreement) GetName

func (sa ServiceAgreement) GetName() string

GetName returns the pluralized "type" of this structure for jsonapi serialization.

func (*ServiceAgreement) SetID

func (sa *ServiceAgreement) SetID(value string) error

SetID is used to set the ID of this structure when deserializing from jsonapi documents.

type Session

type Session struct {
	ID        string    `json:"id" gorm:"primary_key"`
	LastUsed  time.Time `json:"lastUsed" gorm:"index"`
	CreatedAt time.Time `json:"createdAt" gorm:"index"`
}

Session holds the unique id for the authenticated session.

func NewSession

func NewSession() Session

NewSession returns a session instance with ID set to a random ID and LastUsed to to now.

type SessionRequest

type SessionRequest struct {
	Email    string `json:"email"`
	Password string `json:"password"`
}

SessionRequest encapsulates the fields needed to generate a new SessionID, including the hashed password.

type Signature

type Signature [SignatureLength]byte

Signature is a byte array fixed to the size of a signature

func BytesToSignature

func BytesToSignature(b []byte) Signature

BytesToSignature converts an arbitrary length byte array to a Signature

func NewSignature

func NewSignature(s string) (Signature, error)

NewSignature returns a new Signature

func (Signature) Big

func (s Signature) Big() *big.Int

Big returns a big.Int representation

func (Signature) Bytes

func (s Signature) Bytes() []byte

Bytes returns the raw bytes

func (Signature) Format

func (s Signature) Format(state fmt.State, c rune)

Format implements fmt.Formatter

func (Signature) Hex

func (s Signature) Hex() string

Hex returns a hexadecimal string

func (Signature) MarshalJSON

func (s Signature) MarshalJSON() ([]byte, error)

MarshalJSON prints the signature as a hexadecimal encoded string

func (Signature) MarshalText

func (s Signature) MarshalText() ([]byte, error)

MarshalText encodes the signature in hexadecimal

func (*Signature) Scan

func (s *Signature) Scan(value interface{}) error

Scan reads the database value and returns an instance.

func (*Signature) SetBytes

func (s *Signature) SetBytes(b []byte)

SetBytes assigns the byte array to the signature

func (Signature) String

func (s Signature) String() string

String implements the stringer interface and is used also by the logger.

func (*Signature) UnmarshalJSON

func (s *Signature) UnmarshalJSON(input []byte) error

UnmarshalJSON parses a signature from a JSON string

func (*Signature) UnmarshalText

func (s *Signature) UnmarshalText(input []byte) error

UnmarshalText parses the signature from a hexadecimal representation

func (Signature) Value

func (s Signature) Value() (driver.Value, error)

Value returns this instance serialized for database storage.

type Signer

type Signer interface {
	Sign(input []byte) (Signature, error)
}

Signer is used to produce a HMAC signature from an input digest

type SyncEvent

type SyncEvent struct {
	ID        uint `gorm:"primary_key"`
	CreatedAt time.Time
	UpdatedAt time.Time
	Body      string
}

SyncEvent represents an event sourcing style event, which is used to sync data upstream with another service

type TaskRun

type TaskRun struct {
	ID                   string        `json:"id" gorm:"primary_key;not null"`
	JobRunID             string        `json:"-" gorm:"index;not null;type:varchar(36) REFERENCES job_runs(id) ON DELETE CASCADE"`
	Result               RunResult     `json:"result"`
	ResultID             uint          `json:"-"`
	Status               RunStatus     `json:"status"`
	TaskSpec             TaskSpec      `json:"task" gorm:"association_autoupdate:false;association_autocreate:false"`
	TaskSpecID           uint          `json:"-" gorm:"index;not null REFERENCES task_specs(id)"`
	MinimumConfirmations clnull.Uint32 `json:"minimumConfirmations"`
	Confirmations        clnull.Uint32 `json:"confirmations"`
	CreatedAt            time.Time     `json:"-" gorm:"index"`
}

TaskRun stores the Task and represents the status of the Task to be ran.

func (*TaskRun) ApplyResult

func (tr *TaskRun) ApplyResult(result RunResult)

ApplyResult updates the TaskRun's Result and Status

func (*TaskRun) ForLogger

func (tr *TaskRun) ForLogger(kvs ...interface{}) []interface{}

ForLogger formats the TaskRun info for a common formatting in the log.

func (*TaskRun) MarkPendingConfirmations

func (tr *TaskRun) MarkPendingConfirmations()

MarkPendingConfirmations marks the task's status as blocked.

func (*TaskRun) SetError

func (tr *TaskRun) SetError(err error)

SetError sets this task run to failed and saves the error message

func (TaskRun) String

func (tr TaskRun) String() string

String returns info on the TaskRun as "ID,Type,Status,Result".

type TaskSpec

type TaskSpec struct {
	gorm.Model
	JobSpecID     string        `json:"-" gorm:"index;type:varchar(36) REFERENCES job_specs(id)"`
	Type          TaskType      `json:"type" gorm:"index;not null"`
	Confirmations clnull.Uint32 `json:"confirmations"`
	Params        JSON          `json:"params" gorm:"type:text"`
}

TaskSpec is the definition of work to be carried out. The Type will be an adapter, and the Params will contain any additional information that adapter would need to operate.

type TaskSpecRequest

type TaskSpecRequest struct {
	Type          TaskType      `json:"type"`
	Confirmations clnull.Uint32 `json:"confirmations"`
	Params        JSON          `json:"params"`
}

TaskSpecRequest represents a schema for incoming TaskSpec requests as used by the API.

type TaskType

type TaskType string

TaskType defines what Adapter a TaskSpec will use.

func MustNewTaskType

func MustNewTaskType(val string) TaskType

MustNewTaskType instantiates a new TaskType, and panics if a bad input is provided.

func NewTaskType

func NewTaskType(val string) (TaskType, error)

NewTaskType returns a formatted Task type.

func (TaskType) MarshalJSON

func (t TaskType) MarshalJSON() ([]byte, error)

MarshalJSON converts a TaskType to a JSON byte slice.

func (*TaskType) Scan

func (t *TaskType) Scan(value interface{}) error

Scan reads the database value and returns an instance.

func (TaskType) String

func (t TaskType) String() string

String returns this TaskType as a string.

func (*TaskType) UnmarshalJSON

func (t *TaskType) UnmarshalJSON(input []byte) error

UnmarshalJSON converts a bytes slice of JSON to a TaskType.

func (TaskType) Value

func (t TaskType) Value() (driver.Value, error)

Value returns this instance serialized for database storage.

type Tx

type Tx struct {
	ID uint64 `gorm:"primary_key;auto_increment"`

	// SurrogateID is used to look up a transaction using a secondary ID, used to
	// associate jobs with transactions so that we don't double spend in certain
	// failure scenarios
	SurrogateID null.String `gorm:"index;unique"`

	Attempts []*TxAttempt `json:"-"`

	From     common.Address `gorm:"index;not null"`
	To       common.Address `gorm:"not null"`
	Data     []byte         `gorm:"not null"`
	Nonce    uint64         `gorm:"index;not null"`
	Value    *Big           `gorm:"type:varchar(78);not null"`
	GasLimit uint64         `gorm:"not null"`

	// TxAttempt fields manually included; can't embed another primary_key
	Hash        common.Hash `gorm:"not null"`
	GasPrice    *Big        `gorm:"type:varchar(78);not null"`
	Confirmed   bool        `gorm:"not null"`
	SentAt      uint64      `gorm:"not null"`
	SignedRawTx string      `gorm:"type:text;not null"`
}

Tx contains fields necessary for an Ethereum transaction with an additional field for the TxAttempt.

func (Tx) EthTx

func (tx Tx) EthTx(gasPriceWei *big.Int) *types.Transaction

EthTx creates a new Ethereum transaction with a given gasPrice in wei that is ready to be signed.

func (*Tx) String

func (tx *Tx) String() string

String implements Stringer for Tx

type TxAttempt

type TxAttempt struct {
	ID uint64 `gorm:"primary_key;auto_increment"`

	TxID uint64 `gorm:"index;type:bigint REFERENCES txes(id) ON DELETE CASCADE"`
	Tx   *Tx    `json:"-" gorm:"PRELOAD:false;foreignkey:TxID"`

	CreatedAt time.Time `gorm:"index;not null"`

	Hash        common.Hash `gorm:"index;not null"`
	GasPrice    *Big        `gorm:"type:varchar(78);not null"`
	Confirmed   bool        `gorm:"not null"`
	SentAt      uint64      `gorm:"not null"`
	SignedRawTx string      `gorm:"type:text;not null"`
}

TxAttempt is used for keeping track of transactions that have been written to the Ethereum blockchain. This makes it so that if the network is busy, a transaction can be resubmitted with a higher GasPrice.

func (TxAttempt) GetID

func (txa TxAttempt) GetID() string

GetID returns the ID of this structure for jsonapi serialization.

func (TxAttempt) GetName

func (txa TxAttempt) GetName() string

GetName returns the pluralized "type" of this structure for jsonapi serialization.

func (*TxAttempt) SetID

func (txa *TxAttempt) SetID(value string) error

SetID is used to set the ID of this structure when deserializing from jsonapi documents.

func (*TxAttempt) String

func (txa *TxAttempt) String() string

String implements Stringer for TxAttempt

type TxReceipt

type TxReceipt struct {
	BlockNumber *Big        `json:"blockNumber" gorm:"type:numeric"`
	Hash        common.Hash `json:"transactionHash"`
	Logs        []Log       `json:"logs"`
}

TxReceipt holds the block number and the transaction hash of a signed transaction that has been written to the blockchain.

func (TxReceipt) FulfilledRunLog

func (txr TxReceipt) FulfilledRunLog() bool

func (*TxReceipt) Unconfirmed

func (txr *TxReceipt) Unconfirmed() bool

Unconfirmed returns true if the transaction is not confirmed.

type UnsignedServiceAgreement

type UnsignedServiceAgreement struct {
	Encumbrance    Encumbrance
	ID             common.Hash
	RequestBody    string
	JobSpecRequest JobSpecRequest
}

UnsignedServiceAgreement contains the information to sign a service agreement

func NewUnsignedServiceAgreementFromRequest

func NewUnsignedServiceAgreementFromRequest(reader io.Reader) (UnsignedServiceAgreement, error)

NewUnsignedServiceAgreementFromRequest builds the information required to sign a service agreement

type User

type User struct {
	Email          string    `json:"email" gorm:"primary_key"`
	HashedPassword string    `json:"hashedPassword"`
	CreatedAt      time.Time `json:"createdAt" gorm:"index"`
}

User holds the credentials for API user.

func NewUser

func NewUser(email, plainPwd string) (User, error)

NewUser creates a new user by hashing the passed plainPwd with bcrypt.

type ValidationError

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

ValidationError is an error that occurs during validation.

func (*ValidationError) Error

func (e *ValidationError) Error() string

type WebURL

type WebURL url.URL

WebURL contains the URL of the endpoint.

func (WebURL) MarshalJSON

func (w WebURL) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON-encoded string of the given data.

func (*WebURL) Scan

func (w *WebURL) Scan(value interface{}) error

Scan reads the database value and returns an instance.

func (WebURL) String

func (w WebURL) String() string

String delegates to the wrapped URL struct or an empty string when it is nil

func (*WebURL) UnmarshalJSON

func (w *WebURL) UnmarshalJSON(j []byte) error

UnmarshalJSON parses the raw URL stored in JSON-encoded data to a URL structure and sets it to the URL field.

func (WebURL) Value

func (w WebURL) Value() (driver.Value, error)

Value returns this instance serialized for database storage.

type WithdrawalRequest

type WithdrawalRequest struct {
	DestinationAddress common.Address `json:"address"`
	ContractAddress    common.Address `json:"contractAddress"`
	Amount             *assets.Link   `json:"amount"`
}

WithdrawalRequest request to withdraw LINK.

Jump to

Keyboard shortcuts

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