Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add machine module #340

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,28 +1,28 @@
// (c) Cartesi and individual authors (see AUTHORS)
// SPDX-License-Identifier: Apache-2.0 (see LICENSE)

package services
package linewriter

import (
"bytes"
"io"
)

// lineWriter accumulates the received data in a buffer and writes it to the inner writer when it
// LineWriter accumulates the received data in a buffer and writes it to the inner writer when it
// encounters a new line, ignoring empty lines in the process.
// lineWriter assumes the inner writer does not returns an error.
type lineWriter struct {
// LineWriter assumes the inner writer does not returns an error.
type LineWriter struct {
inner io.Writer
buffer bytes.Buffer
}

func newLineWriter(inner io.Writer) *lineWriter {
return &lineWriter{
func New(inner io.Writer) *LineWriter {
return &LineWriter{
inner: inner,
}
}

func (w *lineWriter) Write(data []byte) (int, error) {
func (w *LineWriter) Write(data []byte) (int, error) {
_, err := w.buffer.Write(data)
if err != nil {
// Not possible given bytes.Buffer spec
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// (c) Cartesi and individual authors (see AUTHORS)
// SPDX-License-Identifier: Apache-2.0 (see LICENSE)

package services
package linewriter

import (
"bytes"
Expand All @@ -24,7 +24,7 @@ func (w *mockWriter) Write(p []byte) (int, error) {
type LineWriterSuite struct {
suite.Suite
mock *mockWriter
writer *lineWriter
writer *LineWriter
}

func TestLineWriterSuite(t *testing.T) {
Expand All @@ -33,7 +33,7 @@ func TestLineWriterSuite(t *testing.T) {

func (s *LineWriterSuite) SetupTest() {
s.mock = &mockWriter{}
s.writer = newLineWriter(s.mock)
s.writer = New(s.mock)
}

func (s *LineWriterSuite) TestItWritesLines() {
Expand Down
6 changes: 4 additions & 2 deletions internal/services/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import (
"strings"
"syscall"
"time"

"github.com/cartesi/rollups-node/internal/linewriter"
)

const (
Expand Down Expand Up @@ -43,8 +45,8 @@ type CommandService struct {
func (s CommandService) Start(ctx context.Context, ready chan<- struct{}) error {
cmd := exec.CommandContext(ctx, s.Path, s.Args...)
cmd.Env = s.Env
cmd.Stderr = newLineWriter(commandLogger{s.Name})
cmd.Stdout = newLineWriter(commandLogger{s.Name})
cmd.Stderr = linewriter.New(commandLogger{s.Name})
cmd.Stdout = linewriter.New(commandLogger{s.Name})
cmd.Cancel = func() error {
err := cmd.Process.Signal(syscall.SIGTERM)
if err != nil {
Expand Down
80 changes: 80 additions & 0 deletions pkg/gollup/gollup.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
// (c) Cartesi and individual authors (see AUTHORS)
// SPDX-License-Identifier: Apache-2.0 (see LICENSE)

package gollup

import "github.com/cartesi/rollups-node/pkg/libcmt"

type OutputEmitter interface {
SendVoucher(address [20]byte, value []byte, data []byte) error
SendNotice(data []byte) error
}

type ReportEmitter interface {
SendReport(data []byte) error
}

// ------------------------------------------------------------------------------------------------

type AdvanceHandler func(OutputEmitter, *libcmt.Input) bool

type InspectHandler func(ReportEmitter, *libcmt.Query) bool

type Gollup struct {
rollup *libcmt.Rollup
advanceHandler AdvanceHandler
inspectHandler InspectHandler
}

func NewGollup(advanceHandler AdvanceHandler, inspectHandler InspectHandler) (*Gollup, error) {
rollup, err := libcmt.NewRollup()
if err != nil {
return nil, err
}
return &Gollup{rollup, advanceHandler, inspectHandler}, nil
}

func (gollup *Gollup) Destroy() {
gollup.rollup.Destroy()
}

func (gollup *Gollup) Run() error {
accept := true
for {
finish, err := gollup.rollup.Finish(accept)
if err != nil {
return err
}

switch finish.NextRequestType {
case libcmt.AdvanceStateRequest:
input, err := gollup.rollup.ReadAdvanceState()
if err != nil {
return err
}
accept = gollup.advanceHandler(gollup, input)
case libcmt.InspectStateRequest:
query, err := gollup.rollup.ReadInspectState()
if err != nil {
return err
}
accept = gollup.inspectHandler(gollup, query)
default:
panic("unreachable")
}
}
}

// ------------------------------------------------------------------------------------------------

func (gollup *Gollup) SendVoucher(address [20]byte, value []byte, data []byte) error {
return gollup.rollup.EmitVoucher(address, value, data)
}

func (gollup *Gollup) SendNotice(data []byte) error {
return gollup.rollup.EmitNotice(data)
}

func (gollup *Gollup) SendReport(data []byte) error {
return gollup.rollup.EmitReport(data)
}
163 changes: 163 additions & 0 deletions pkg/libcmt/libcmt.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
// (c) Cartesi and individual authors (see AUTHORS)
// SPDX-License-Identifier: Apache-2.0 (see LICENSE)

package libcmt

// #cgo LDFLAGS: -lcmt
// #include <stdlib.h>
// #include <string.h>
// #include "libcmt/rollup.h"
// #include "libcmt/io.h"
import "C"
import (
"fmt"
"unsafe"
)

type RequestType = uint8

const AdvanceStateRequest RequestType = C.CMT_IO_REASON_ADVANCE
const InspectStateRequest RequestType = C.CMT_IO_REASON_INSPECT

type Finish struct {
AcceptPreviousRequest bool
NextRequestType RequestType
NextRequestPayloadLength uint32
}

type Input struct {
Sender [20]byte
BlockNumber uint64
BlockTimestamp uint64
Index uint64
Data []byte
}

type Query struct {
Data []byte
}

// ------------------------------------------------------------------------------------------------

type Rollup struct {
inner *C.cmt_rollup_t
}

func NewRollup() (*Rollup, error) {
var rollup C.cmt_rollup_t
errno := C.cmt_rollup_init(&rollup)
return &Rollup{inner: &rollup}, toError(errno)
}

func (rollup *Rollup) Destroy() {
C.cmt_rollup_fini(rollup.inner)
}

func (rollup *Rollup) Finish(accept bool) (*Finish, error) {
finish := C.cmt_rollup_finish_t{
accept_previous_request: C.bool(accept),
}

errno := C.cmt_rollup_finish(rollup.inner, &finish)
if err := toError(errno); err != nil {
return nil, err
}

return &Finish{
AcceptPreviousRequest: bool(finish.accept_previous_request),
NextRequestType: RequestType(finish.next_request_type),
NextRequestPayloadLength: uint32(finish.next_request_payload_length),
}, nil
}

func (rollup *Rollup) EmitVoucher(address [20]byte, value []byte, voucher []byte) error {
addressLength, addressData := C.uint(20), C.CBytes(address[:])
defer C.free(addressData)

valueLength, valueData := C.uint(len(value)), C.CBytes(value)
defer C.free(valueData)

voucherLength, voucherData := C.uint(len(voucher)), C.CBytes(voucher)
defer C.free(voucherData)

return toError(C.cmt_rollup_emit_voucher(rollup.inner,
addressLength, addressData,
valueLength, valueData,
voucherLength, voucherData,
))
}

func (rollup *Rollup) EmitNotice(notice []byte) error {
length, data := C.uint(len(notice)), C.CBytes(notice)
defer C.free(data)
return toError(C.cmt_rollup_emit_notice(rollup.inner, length, data))
}

func (rollup *Rollup) EmitReport(report []byte) error {
length, data := C.uint(len(report)), C.CBytes(report)
defer C.free(data)
return toError(C.cmt_rollup_emit_report(rollup.inner, length, data))
}

func (rollup *Rollup) EmitException(exception []byte) error {
length, data := C.uint(len(exception)), C.CBytes(exception)
defer C.free(data)
return toError(C.cmt_rollup_emit_exception(rollup.inner, length, data))
}

func (rollup *Rollup) ReadAdvanceState() (*Input, error) {
var advance C.cmt_rollup_advance_t
errno := C.cmt_rollup_read_advance_state(rollup.inner, &advance)
if err := toError(errno); err != nil {
return nil, err
}
// TODO: should I free inner.data?

var sender [20]byte
for i, v := range advance.sender {
sender[i] = byte(v)
}

return &Input{
Data: C.GoBytes(advance.data, C.int(advance.length)),
Sender: sender,
BlockNumber: uint64(advance.block_number),
BlockTimestamp: uint64(advance.block_timestamp),
Index: uint64(advance.index),
}, nil
}

func (rollup *Rollup) ReadInspectState() (*Query, error) {
var query C.cmt_rollup_inspect_t
errno := C.cmt_rollup_read_inspect_state(rollup.inner, &query)
if err := toError(errno); err != nil {
return nil, err
}
// TODO: should I free query.data?

return &Query{Data: C.GoBytes(query.data, C.int(query.length))}, nil
}

func (rollup *Rollup) LoadMerkle(path string) error {
s := C.CString(path)
defer C.free(unsafe.Pointer(s))
return toError(C.cmt_rollup_load_merkle(rollup.inner, s))
}

func (rollup *Rollup) SaveMerkle(path string) error {
s := C.CString(path)
defer C.free(unsafe.Pointer(s))
return toError(C.cmt_rollup_save_merkle(rollup.inner, s))
}

// ------------------------------------------------------------------------------------------------

func toError(errno C.int) error {
if errno < 0 {
s := C.strerror(-errno)
defer C.free(unsafe.Pointer(s))
return fmt.Errorf("%s (%d)", C.GoString(s), errno)
} else {
return nil
}
}
Loading
Loading