baas

package module
v0.0.0-...-bd0efcb Latest Latest
Warning

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

Go to latest
Published: Dec 14, 2020 License: MIT Imports: 11 Imported by: 0

README

BAAS block as a service

curl -XPOST http://127.0.0.1:14200/applications -H "Content-Type=application/json" -d '{

"name":"智慧农业", "description":"区块链系统BAAS服务", "storageEngine":"bolt", "storageAccessKey":"mmaskdjfasdf", "storageSecretKey":"masdfsafdsafdsaf", "storageRegion":"XiongAN", "deliveryUrl":"http://127.0.0.1:4200/api" }' {"data":{"id":"954348da-948c-4bb8-86c2-d9a53ef395ff","name":"智慧农业","description":"区块链系统BAAS服务","storageAccessKey":"mmaskdjfasdf","storageBucket":"","storageEndpoint":"","storageRegion":"XiongAN","storageEngine":"bolt","cdnUrl":"http://127.0.0.1:4200/api","createdAt":"2020-08-13T14:54:38.776070197+08:00","updatedAt":"2020-08-13T14:54:38.776070317+08:00"}}

curl -XPOST http://127.0.0.1:14200 -d '{

"application_id":"954348da-948c-4bb8-86c2-d9a53ef395ff", "userid":"jihua.gao@gmail.com", "password":"qweasdzxc", "name":"西方大熊" }'

{"status":0,"data":{"id":"d212ca92-310a-47ad-a014-7767d8d5a8a2","email":"jihua.gao@gmail.com","name":"","application_id":"954348da-948c-4bb8-86c2-d9a53ef395ff","description":"","address":"0x360af35eac2e66420905a2e2f451301b912ca663","createdAt":"2020-08-13T14:57:11.068651697+08:00","updatedAt":"2020-08-13T14:57:11.068652169+08:00"}}

curl -XPOST http://127.0.0.1:14200/api/baas/getKey -d '{

"userid":"jihua.gao@gmail.com", "password":"qweasdzxc", "application_id":"954348da-948c-4bb8-86c2-d9a53ef395ff" }' {"data":{"key":"c72a8cf72de549944f1df31bb3f1f19d6dd65fac88e76b3e79a0c877fe12e5ef"},"status":1}

curl -XPOST http://127.0.0.1:14200/api/baas/writeMsg -d '{

"userId":"jihua.gao@gmail.com", "toUserId":"jihua.gao@gmail.com", "message":"大马哈上线了", "password":"qweasdzxc" }' {"data":{"txhash":"0xe4a5f20b6645aafc8bcf016976cd175681239e9638504cd58b72481878dd7915"},"error":"","status":1}

curl -XPOST http://127.0.0.1:14200/api/baas/readMsg -d '{

"hash":"0xe4a5f20b6645aafc8bcf016976cd175681239e9638504cd58b72481878dd7915" }' {"data":{"timestamp":"2020-08-13 15:09:59 +0800 CST","txhash":"大马哈上线了"},"error":"","status":1}

curl -XPOST http://127.0.0.1:4200/api/baas/getTxByHash

{ "hash":"0x2dbbf0a93af9f03546b9d2b608d4888221fec8997433d3c78d1216e8bc65d3da" }

Documentation

Index

Constants

View Source
const (
	StorageEngineWasabi       = "wasabi"
	StorageEngineDigitalOcean = "digital_ocean"
	StorageEngineS3           = "s3"
	StorageEngineB2           = "b2"
	StorageEngineAzureBlob    = "azure_blob"
	StorageEngineIPFS         = "ipfs"
	StorageEngineBolt         = "bolt"
)
View Source
const (
	BlockEngine            = "http://127.0.0.1:8545"
	GasMax                 = 90000000
	GasLimit               = 21000
	GasMsgLimit            = 1800000
	GasERC20Limit          = 500000
	GasERC721Limit         = 1000000
	GasERC721TransferLimit = 100000
)
View Source
const (
	ErrUnauthorized = Error("unauthorized")
	ErrInternal     = Error("internal error")
	ErrInvalidDate  = Error("invalid date")
	ErrNotFound     = Error("resource not found")
	ErrBadRequest   = Error("bad request")
	ErrInvalidJSON  = Error("invalid json")
)

General errors.

View Source
const (
	ErrApplicationNotFound  = Error("application_id not found")
	ErrApplicationNameTaken = Error("application name taken")
)

Application errors

View Source
const (
	ErrBucketNotFound    = Error("bucket does not exist")
	ErrInvalidBucketName = Error("invalid bucket name")
	ErrInvalidStorageKey = Error("invalid api keys or api keys do not have correct permissions")
)

Storage errors

View Source
const (
	ErrFileNotFound            = Error("file not found")
	ErrFileToLargeToTransform  = Error("file is to large to transform")
	ErrTransformationNotUnique = Error("transformation is not unique")
)

File errors

View Source
const (
	ErrBaasNoSuchUser            = Error("userId does not exist")
	ErrBaasUserNameTaken         = Error("userId is already exist")
	ErrBaasInvalidPassword       = Error("invalid password")
	ErrBaasParameterNotFound     = Error("parameter is no valid")
	ErrBassContractCmdNotFound   = Error("invalid contract action")
	ErrBaasInvalidQuantity       = Error("Quantity is invalid")
	ErrBaasContractInValid       = Error("The Contract data is invalid")
	ErrBaasApplicationIDRequired = Error("Application ID is required")
	ErrBaasCipherTextRequired    = Error("invalid cipherText")
	ErrBaasNotEnoughMoney        = Error("Account doesn't have enough gas")
	ErrBaasQueryNoResult         = Error("No result")
)

Blockchain baas error

View Source
const DateLayout = "2006-01-02"
View Source
const DefaultFilePaginationLimit = 25
View Source
const (
	ErrAuthorizationHeaderMissing = Error("authorization header is missing")
)
View Source
const (
	ErrUsageNotFound = Error("usage not found")
)

Usage errors

Variables

View Source
var (
	BlockChainServer        = BlockEngine
	DelplyContractGas int64 = 5000000
	OriginTokenOP     int64 = 545228
	ERC20TokenOP      int64 = 100000
	ERC20TokenSend    int64 = 500000
	ERC721TokenOP     int64 = 500000
	ERC721TokenMint   int64 = 700000
	ERC721TokenSend   int64 = 700000
)
View Source
var (
	PageSize = 25
)

Functions

func GenerateSalt

func GenerateSalt() ([]byte, error)

randSalt generates 16 * 8 bits of data for a random salt

func PKCS5Padding

func PKCS5Padding(src []byte, blockSize int) []byte

func PKCS5UnPadding

func PKCS5UnPadding(src []byte) []byte

func RandInt

func RandInt(min, max int) int

func RandStr

func RandStr(length int) string

Types

type Application

type Application struct {
	ID               string
	Name             string
	Description      string
	StorageAccessKey string
	StorageSecretKey string
	StorageBucket    string
	StorageEndpoint  string
	StorageRegion    string
	StorageEngine    string
	DeliveryURL      string
	CreatedAt        time.Time
	UpdatedAt        time.Time
}

type ApplicationService

type ApplicationService interface {
	Create(ctx context.Context, n *NewApplication) (*Application, error)
	Application(ctx context.Context, id string) (*Application, error)
	Applications(ctx context.Context, sinceID string, limit int) ([]*Application, error)
	Delete(ctx context.Context, id string) error
	Update(ctx context.Context, u *UpdateApplication) (*Application, error)
	FileBlobStorage(engine, accessKey, secretKey, region, endpoint string) (FileBlobStorage, error)
}

ApplicationService defines the business logic for dealing with all aspects of an application.

type ApplicationStorage

type ApplicationStorage interface {
	Store(ctx context.Context, n *NewApplication) (*Application, error)
	Application(ctx context.Context, id string) (*Application, error)
	Applications(ctx context.Context, sinceID string, limit int) ([]*Application, error)
	Delete(ctx context.Context, id string) error
	Update(ctx context.Context, u *UpdateApplication) (*Application, error)
}

ApplicationStorage handles communication with the database for handling applications.

type BAASUser

type BAASUser struct {
	ID               string
	Email            string
	Name             string
	Description      string
	StorageAccessKey string
	StorageSecretKey string
	StorageBucket    string
	ApplicationID    string
	Address          string
	Password         string
	PrivateKey       string
	Salt             string
	CipherText       string
	Rv               string
	CreatedAt        time.Time
	UpdatedAt        time.Time
}

type Block

type Block struct {
	ID               string
	Name             string
	Description      string
	StorageAccessKey string
	StorageSecretKey string
	StorageBucket    string
	StorageEndpoint  string
	StorageRegion    string
	StorageEngine    string
	DeliveryURL      string
	CreatedAt        time.Time
	UpdatedAt        time.Time
}

type BlockService

type BlockService interface {
	Create(ctx context.Context, n *NewBAASUser) (*BAASUser, error)
	Import(ctx context.Context, n *NewBAASUser) (*BAASUser, error)
	ChangePassword(ctx context.Context, userId, oldPassword, newPassword string) error
	DeleteBAASUser(ctx context.Context, id string) error
	UpdateBAASUser(ctx context.Context, u *UpdateBAASUser) (*BAASUser, error)
	GetKey(ctx context.Context, id, password, ciper string) (string, error)
	DeleteKey(ctx context.Context, id, passwd, applicationid string) error
	GetAddress(ctx context.Context, id, password string) (string, error)
	RecoverKey(ctx context.Context, id string) (string, error)
	GetBalance(ctx context.Context, addr string) (string, error)
	SendToken(ctx context.Context, userid, password, toAddr, value, msg, encode string, gas int64) (string, error)
	WriteMsg(ctx context.Context, addr, password, toAddr, msg string, gas int64) (string, error)
	ReadMsg(ctx context.Context, hash, encode string) (string, string, error)
	GetTxByHash(ctx context.Context, hash string) (string, error)
	//===================erc721 ====================================
	GetErc721Info(ctx context.Context, addr string) (map[string]interface{}, error)
	GetErc721Balance(ctx context.Context, addr, contractAddr string) (string, error)
	GetErc721TotalSupply(ctx context.Context, addr string) (string, error)
	CreateErc721Token(ctx context.Context, userid, password, addr, tokenid, meta, property string, gas int64) (string, error)
	SetErc721TokenProperty(ctx context.Context, userid, password, addr, tokenid, property string, gas int64) (string, error)
	GetErc721TokenProperty(ctx context.Context, addr, tokenid string) (string, error)
	SendErc721Token(ctx context.Context, addr, password, contractaddr, tokeid, memo, targetuser string, gas int64) (string, error)
	GetSendErc721TokenMemo(ctx context.Context, contractaddr, tokeid, hash string) (string, error)
	GetErc721MetaData(ctx context.Context, addr, tokenid string) (string, error)
	AddErc721TokenMemo(ctx context.Context, user, password, contract, tokenid, memo string, gas int64) (string, error)
	GetErc721TokenMemoList(ctx context.Context, contractaddr, tokenid string) (string, error)
	GetUserErc721TokenList(ctx context.Context, userid, contractaddr string) (string, error)
	CreateERC721Contract(ctx context.Context, userid, password, name, symbol, class string) (string, string, error) //user create new ERC721 contranct with type
	//===================erc20 ====================================
	DeployERC20Contract(ctx context.Context, userid, password, name, symbol, class string, totalsupply uint64, decimal uint8, capacity uint64) (string, string, error) //user create new ERC20 contranct with type
	GetErc20TotalSupply(ctx context.Context, addr string) (string, error)
	GetErc20Decimal(ctx context.Context, addr string) (string, error)
	GetErc20Info(ctx context.Context, addr string) (map[string]interface{}, error)
	GetErc20Balance(ctx context.Context, userid, addr string) (string, error)
	SendErc20Token(ctx context.Context, addr, password, toAddr, contract, memo string, value float64, gas int64) (string, error)
	ApproveErc20(ctx context.Context, addr, password, toAddr, contract string, value float64, gas int64) (string, error)
	AllowanceErc20(ctx context.Context, addr, toAddr, contract string) (string, error)
	IncreaseAllowanceErc20(ctx context.Context, addr, password, toAddr, contract string, value float64, gas int64) (string, error)
	DecresaseAllowanceErc20(ctx context.Context, addr, password, toAddr, contract string, value float64, gas int64) (string, error)
	GetErc20TxMemo(ctx context.Context, hash string) (string, error)
	BurnErc20(ctx context.Context, addr, password, contract string, value float64, gas int64) (string, error)
	PauseErc20(ctx context.Context, addr, password, contract string, value bool, gas int64) (string, error)
	MintErc20(ctx context.Context, addr, password, contract string, value float64, gas int64) (string, error)
	GetErc20PauseStatus(ctx context.Context, contract string) (string, error)
	TransferFromErc20(ctx context.Context, user, password, fromaddr, toAddr, contract, memo string, value float64, gas int64) (string, error)
	// ==================++Erc20 analysis
	GetERC20TxByUserAddress(ctx context.Context, userid, contract, page, pagesize string) (string, error)
	GetERC20TxList(ctx context.Context, contract, page, pagesize string) (string, error)
	//CreateErc20Token(ctx context.Context, addr string) (string, error)
	// The following the some statistics functions
	//GetErc721Property(ctx context.Context, addr, tokenid string) (string, error)
	//===================analysis and utility ====================================
	GetApplicationUsers(ctx context.Context, id string, page, limit int) ([]*BAASUser, error)
	GetTx(ctx context.Context, addr string) (*BlockTx, error)
	GetBlockNumber(ctx context.Context) (string, error)
	GetAddressFromPK(ctx context.Context, pk string) (string, error)
	GetKeyStoreFromPK(ctx context.Context, pk, password string) (string, error)
	GetPKFromKeyStore(ctx context.Context, keystore, password string) (string, error)
	//FileBlobStorage(engine, accessKey, secretKey, region, endpoint string) (FileBlobStorage, error)
	DecryptKey(origin, cipherFromWeb, cipherFromDb, rv, salt string) (string, error)
	GetTxByUserAddress(ctx context.Context, usrid, page, size string) (string, error)                     // query backend system for address tx record
	GetPeerToPeerTxByUserAddress(ctx context.Context, usrid, targetid, page, size string) (string, error) // query backend system for address tx record
	GetErc721TxList(ctx context.Context, addr, page, size string) (string, error)
	GetErc721TokenTxList(ctx context.Context, contract, tokenid, page, size string) (string, error)
	GetErc721TxListByUser(ctx context.Context, userid, contract, page, size string) (string, error)
	GetErc721TokenTxListByUser(ctx context.Context, userid, contract, tokenid, page, size string) (string, error)
}

ApplicationService defines the business logic for dealing with all aspects of an application.

type BlockStorage

type BlockStorage interface {
	Store(ctx context.Context, n *NewBAASUser) (*BAASUser, error)
	UpdatePassword(ctx context.Context, id, old, new string) error
	GetKey(ctx context.Context, id, password string) (string, string, string, string, error)
	DeleteKey(ctx context.Context, id, password string) error
	GetAddress(ctx context.Context, id, password string) (string, error)
	// address, origpk, rv,cipher,salt
	GetAddressByService(ctx context.Context, id, password string) (string, string, string, string, string, error)
	//Delete(ctx context.Context, id string) error
	GetApplicationId(ctx context.Context, id string) (string, error)
	Update(ctx context.Context, u *UpdateBAASUser) (*BAASUser, error)
	ApplicationUsers(ctx context.Context, id string, page, limit int) ([]*BAASUser, error)
}

blockStorage handles communication with the database for handling block.

type BlockTx

type BlockTx struct {
	Type   string
	Filter string
	Data   []interface{}
}

type EncryptionService

type EncryptionService interface {
	Encrypt(plaintext []byte) ([]byte, error)
	EncryptToString(plaintext []byte) (string, error)
	Decrypt(cipherText []byte) ([]byte, error)
	DecryptString(cipherText string) ([]byte, error)
	Config(key []byte, iv []byte)
}

EncryptionService manages the encrypting and decrypting of data

type Error

type Error string

Error represents a Mahi error.

func (Error) Error

func (e Error) Error() string

Error returns the error message.

type File

type File struct {
	ID            string
	ApplicationID string
	Filename      string
	FileBlobID    string
	Size          int64
	MIMEType      string
	MIMEValue     string
	Extension     string
	URL           string
	Hash          string
	Width         int
	Height        int
	CreatedAt     time.Time
	UpdatedAt     time.Time
}

File holds all the "meta" data of a file. From its type and size to who uploaded it and what application it was uploaded to.

func (*File) IsImage

func (f *File) IsImage() bool

func (*File) IsTransformable

func (f *File) IsTransformable() bool

type FileBlob

type FileBlob struct {
	ID        string
	Data      io.ReadCloser
	MIMEValue string
	Size      int64

	// TempFileName this is used to determine if we need to delete the temp file after using the FileBlob
	TempFileName string
	Hash         string
}

FileBlob is holds the properties needed for the blob of a file.

func (*FileBlob) Bytes

func (b *FileBlob) Bytes(p []byte) (int, error)

Bytes transforms the data of the FileBlob into a byte array

func (*FileBlob) Close

func (b *FileBlob) Close() error

Close closes the io.ReadCloser and deletes the temp file if one was used

func (*FileBlob) IsImage

func (b *FileBlob) IsImage() bool

func (*FileBlob) IsTransformable

func (b *FileBlob) IsTransformable() bool

type FileBlobStorage

type FileBlobStorage interface {
	Upload(ctx context.Context, bucket string, b *FileBlob) error
	CreateBucket(ctx context.Context, bucket string) error
	FileBlob(ctx context.Context, bucket, id, tempDir string) (*FileBlob, error)
}

type FileServeService

type FileServeService interface {
	Serve(ctx context.Context, path *url.URL, opts TransformationOption) (*FileBlob, error)
}

FileServeService handles serving the file over http

type FileService

type FileService interface {
	Create(ctx context.Context, n *NewFile) (*File, error)
	File(ctx context.Context, id string) (*File, error)
	ApplicationFiles(ctx context.Context, applicationID, sinceID string, limit int) ([]*File, error)
	Delete(ctx context.Context, id string) error
}

FileService defines the business logic for dealing with all aspects of a file.

type FileStorage

type FileStorage interface {
	Store(ctx context.Context, n *NewFile) (*File, error)
	File(ctx context.Context, id string) (*File, error)
	FileByFileBlobID(ctx context.Context, fileBlobID string) (*File, error)
	ApplicationFiles(ctx context.Context, applicationID, sinceID string, limit int) ([]*File, error)
	Delete(ctx context.Context, id string) error
}

FileStorage handles communication with the database for handling files.

type NewApplication

type NewApplication struct {
	Name             string
	Description      string
	StorageAccessKey string
	StorageSecretKey string
	StorageBucket    string
	StorageEndpoint  string
	StorageRegion    string
	StorageEngine    string
	DeliveryURL      string
}

type NewBAASUser

type NewBAASUser struct {
	Email            string
	Name             string
	Description      string
	StorageAccessKey string
	StorageSecretKey string
	StorageBucket    string
	ApplicationID    string
	Address          string
	PrivateKey       string
	CipherText       string
	Rv               string
	Salt             string
	Password         string
	Key              string
}

type NewFile

type NewFile struct {
	ApplicationID string
	Filename      string
	FileBlobID    string
	Size          int64
	MIMEType      string
	MIMEValue     string
	Extension     string
	URL           string
	Hash          string
	Width         int
	Height        int
}

NewFile is a helper struct for creating a new file

func (*NewFile) IsImage

func (f *NewFile) IsImage() bool

type NewTransformation

type NewTransformation struct {
	ApplicationID string
	FileID        string
	Actions       TransformationOption
}

type NewUsage

type NewUsage struct {
	ApplicationID         string
	Transformations       int64
	UniqueTransformations int64
	Bandwidth             int64
	Storage               int64
	FileCount             int64
	UserCount             int64
	TxCount               int64
	StartDate             time.Time
	EndDate               time.Time
}

type TotalUsage

type TotalUsage struct {
	Transformations       int64
	UniqueTransformations int64
	Bandwidth             int64
	Storage               int64
	FileCount             int64
	Encryption            int64
	TxCount               int64
	UserCount             int64
	StartDate             time.Time
	EndDate               time.Time
}

type TransformService

type TransformService interface {
	Transform(ctx context.Context, f *File, blob *FileBlob, opts TransformationOption) (*FileBlob, error)
	MakeWaterInImage(ctx context.Context, ff *File, blob *FileBlob, text string) (*FileBlob, error)
	VerifyWaterInImage(ctx context.Context, f *File, blob *FileBlob, origf *File, origblob *FileBlob) (*FileBlob, error)
}

type TransformStorage

type TransformStorage interface {
	Store(ctx context.Context, n *NewTransformation) (*Transformation, error)
}

type Transformation

type Transformation struct {
	ID            string
	ApplicationID string
	FileID        string
	Actions       TransformationOption
	CreatedAt     time.Time
	UpdatedAt     time.Time
}

type TransformationOption

type TransformationOption struct {
	// Width
	Width int
	// Height
	Height int
	// Format
	Format string
	// Quality the quality of the JPEG image defaults to 80.
	Quality int
	//  Compression compression for a PNG image defaults to 6.
	Compression int
	// Crop uses lib vips smart crop to crop image
	Crop bool
	// Rotate image rotation angle. Must be a multiple of 90
	Rotate int
	// Flip flips an image
	Flip bool
	// Flop flops an image
	Flop bool
	// Zoom
	Zoom int
	// black and white
	BW bool
	// 是否加水印
	WM bool
	// 水印文字
	WMText string
	//校验WM
	WMV bool
	//Origin
	Origin string
}

type UpdateApplication

type UpdateApplication struct {
	ID          string
	Name        string
	Description string
}

type UpdateBAASUser

type UpdateBAASUser struct {
	ID          string
	Email       string
	UserName    string
	Description string
	Cmd         string
	Address     string
	PrivateKey  string
	Password    string
}

type UpdateUsage

type UpdateUsage struct {
	ApplicationID         string
	Transformations       int64
	UniqueTransformations int64
	Bandwidth             int64
	Storage               int64
	FileCount             int64
	TxCount               int64
	UserCount             int64
	StartDate             time.Time
	EndDate               time.Time
}

type UploadService

type UploadService interface {
	Upload(ctx context.Context, r *multipart.Reader) (*File, error)
	ChunkUpload(ctx context.Context, r *multipart.Reader) error
	CompleteChunkUpload(ctx context.Context, applicationID, uploadID, filename string) (*File, error)
}

type Usage

type Usage struct {
	ID                    string
	ApplicationID         string
	Transformations       int64
	BlockChains           int64
	UniqueTransformations int64
	Bandwidth             int64
	Storage               int64
	FileCount             int64
	EncryptionCount       int64
	UserCount             int64
	TxCount               int64
	StartDate             time.Time
	EndDate               time.Time
	CreatedAt             time.Time
	UpdatedAt             time.Time
}

type UsageService

type UsageService interface {
	Update(ctx context.Context, u *UpdateUsage) error
	Usages(ctx context.Context, startDate, endDate time.Time) ([]*TotalUsage, error)
	ApplicationUsages(ctx context.Context, applicationID string, startTime, endTime time.Time) ([]*Usage, error)
}

type UsageStorage

type UsageStorage interface {
	Update(ctx context.Context, u *UpdateUsage) (*Usage, error)
	Usages(ctx context.Context, startDate, endDate time.Time) ([]*TotalUsage, error)
	ApplicationUsages(ctx context.Context, applicationID string, startTime, endTime time.Time) ([]*Usage, error)
}

Directories

Path Synopsis
adapter
aes
gm
s3
cmd
core
libs
transport

Jump to

Keyboard shortcuts

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