repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
---|---|---|
rahuljaswa/Snapp | Pod/Classes/RJCoreDataManager.h | <reponame>rahuljaswa/Snapp
//
// RJCoreDataManager.h
// Community
//
#import "RJDataMarshaller.h"
#import <CoreData/CoreData.h>
#import <Foundation/Foundation.h>
@class RJRemoteObjectCategory;
@class RJRemoteObjectUser;
@interface RJCoreDataManager : NSObject
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
- (void)marshallPFObjects:(NSArray *)pfObjects relation:(RJDataMarshallerPFRelation)relation targetUser:(RJRemoteObjectUser *)targetUser targetCategory:(RJRemoteObjectCategory *)targetCategory completion:(void (^)(void))completion;
- (void)setUpCoreData;
+ (instancetype)sharedInstance;
@end
|
rahuljaswa/Snapp | Pod/Classes/RJManagedObjectPostCategory.h | <gh_stars>0
//
// RJManagedObjectPostCategory.h
// Community
//
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
@class RJManagedObjectImage;
@class RJManagedObjectPost;
@class RJManagedObjectUser;
@interface RJManagedObjectPostCategory : NSManagedObject
@property (nonatomic, retain) NSDate *createdAt;
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *objectId;
@property (nonatomic, retain) RJManagedObjectImage *image;
@property (nonatomic, retain) NSSet *followers;
@property (nonatomic, retain) NSSet *posts;
@end
@interface RJManagedObjectPostCategory (CoreDataGeneratedAccessors)
- (void)addFollowersObject:(RJManagedObjectUser *)value;
- (void)removeFollowersObject:(RJManagedObjectUser *)value;
- (void)addFollowers:(NSSet *)values;
- (void)removeFollowers:(NSSet *)values;
- (void)addPostsObject:(RJManagedObjectPost *)value;
- (void)removePostsObject:(RJManagedObjectPost *)value;
- (void)addPosts:(NSSet *)values;
- (void)removePosts:(NSSet *)values;
@end
|
rahuljaswa/Snapp | Pod/Classes/RJManagedObjectUser.h | <reponame>rahuljaswa/Snapp
//
// RJManagedObjectUser.h
// Community
//
#import <CoreData/CoreData.h>
#import <Foundation/Foundation.h>
FOUNDATION_EXPORT NSString *const kRJUserChangedBlockSettingsNotification;
FOUNDATION_EXPORT NSString *const kRJUserLoggedInNotification;
FOUNDATION_EXPORT NSString *const kRJUserLoggedOutNotification;
@class RJManagedObjectComment;
@class RJManagedObjectFlag;
@class RJManagedObjectImage;
@class RJManagedObjectLike;
@class RJManagedObjectMessage;
@class RJManagedObjectPost;
@class RJManagedObjectPostCategory;
@class RJManagedObjectThread;
@class RJManagedObjectUser;
@interface RJManagedObjectUser : NSManagedObject
@property (nonatomic, retain) NSDate *createdAt;
@property (nonatomic, retain) NSNumber *currentUser;
@property (nonatomic, retain) RJManagedObjectImage *image;
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *objectId;
@property (nonatomic, retain) NSNumber *skeleton;
@property (nonatomic, retain) NSSet *blockedUsers;
@property (nonatomic, retain) NSSet *comments;
@property (nonatomic, retain) NSSet *flags;
@property (nonatomic, retain) NSSet *followingCategories;
@property (nonatomic, retain) NSSet *followers;
@property (nonatomic, retain) NSSet *followingUsers;
@property (nonatomic, retain) NSSet *likes;
@property (nonatomic, retain) NSSet *messages;
@property (nonatomic, retain) NSSet *posts;
@property (nonatomic, retain) NSSet *readMessages;
@property (nonatomic, retain) NSSet *readThreads;
@property (nonatomic, retain) NSSet *threads;
+ (instancetype)currentUser;
@end
@interface RJManagedObjectUser (CoreDataGeneratedAccessors)
- (void)addBlockedUsersObject:(RJManagedObjectUser *)value;
- (void)removeBlockedUsersObject:(RJManagedObjectUser *)value;
- (void)addBlockedUsers:(NSSet *)values;
- (void)removeBlockedUsers:(NSSet *)values;
- (void)addCommentsObject:(RJManagedObjectComment *)value;
- (void)removeCommentsObject:(RJManagedObjectComment *)value;
- (void)addComments:(NSSet *)values;
- (void)removeComments:(NSSet *)values;
- (void)addFlagsObject:(RJManagedObjectFlag *)value;
- (void)removeFlagsObject:(RJManagedObjectFlag *)value;
- (void)addFlags:(NSSet *)values;
- (void)removeFlags:(NSSet *)values;
- (void)addFollowingCategoriesObject:(RJManagedObjectPostCategory *)value;
- (void)removeFollowingCategoriesObject:(RJManagedObjectPostCategory *)value;
- (void)addFollowingCategories:(NSSet *)values;
- (void)removeFollowingCategories:(NSSet *)values;
- (void)addFollowersObject:(RJManagedObjectUser *)value;
- (void)removeFollowersObject:(RJManagedObjectUser *)value;
- (void)addFollowers:(NSSet *)values;
- (void)removeFollowers:(NSSet *)values;
- (void)addFollowingUsersObject:(RJManagedObjectUser *)value;
- (void)removeFollowingUsersObject:(RJManagedObjectUser *)value;
- (void)addFollowingUsers:(NSSet *)values;
- (void)removeFollowingUsers:(NSSet *)values;
- (void)addLikesObject:(RJManagedObjectLike *)value;
- (void)removeLikesObject:(RJManagedObjectLike *)value;
- (void)addLikes:(NSSet *)values;
- (void)removeLikes:(NSSet *)values;
- (void)addMessagesObject:(RJManagedObjectMessage *)value;
- (void)removeMessagesObject:(RJManagedObjectMessage *)value;
- (void)addMessages:(NSSet *)values;
- (void)removeMessages:(NSSet *)values;
- (void)addPostsObject:(RJManagedObjectPost *)value;
- (void)removePostsObject:(RJManagedObjectPost *)value;
- (void)addPosts:(NSSet *)values;
- (void)removePosts:(NSSet *)values;
- (void)addReadMessagesObject:(RJManagedObjectMessage *)value;
- (void)removeReadMessagesObject:(RJManagedObjectMessage *)value;
- (void)addReadMessages:(NSSet *)values;
- (void)removeReadMessages:(NSSet *)values;
- (void)addReadThreadsObject:(RJManagedObjectThread *)value;
- (void)removeReadThreadsObject:(RJManagedObjectThread *)value;
- (void)addReadThreads:(NSSet *)values;
- (void)removeReadThreads:(NSSet *)values;
- (void)addThreadsObject:(RJManagedObjectThread *)value;
- (void)removeThreadsObject:(RJManagedObjectThread *)value;
- (void)addThreads:(NSSet *)values;
- (void)removeThreads:(NSSet *)values;
@end
|
rahuljaswa/Snapp | Pod/Classes/RJManagedObjectMessage.h | //
// RJManagedObjectMessage.h
// NINEXX
//
// Created by <NAME> on 2/28/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
@class RJManagedObjectThread;
@class RJManagedObjectUser;
@interface RJManagedObjectMessage : NSManagedObject
@property (nonatomic, retain) NSDate *createdAt;
@property (nonatomic, retain) NSString *objectId;
@property (nonatomic, retain) NSString *text;
@property (nonatomic, retain) RJManagedObjectThread *thread;
@property (nonatomic, retain) RJManagedObjectThread *threadWhereLastMessage;
@property (nonatomic, retain) NSSet *readReceipts;
@property (nonatomic, retain) RJManagedObjectUser *sender;
@end
@interface RJManagedObjectMessage (CoreDataGeneratedAccessors)
- (void)addReadReceiptsObject:(RJManagedObjectUser *)value;
- (void)removeReadReceiptsObject:(RJManagedObjectUser *)value;
- (void)addReadReceipts:(NSSet *)values;
- (void)removeReadReceipts:(NSSet *)values;
@end
|
rahuljaswa/Snapp | Pod/Classes/RJSettingsViewController.h | <filename>Pod/Classes/RJSettingsViewController.h
//
// RJSettingsViewController.h
// Community
//
#import <UIKit/UIKit.h>
@class RJSettingsViewController;
@protocol RJSettingsViewControllerDelegate <NSObject>
- (void)settingsViewControllerDidLogout:(RJSettingsViewController *)settingsViewController;
@end
@interface RJSettingsViewController : UITableViewController
@property (nonatomic, weak) id<RJSettingsViewControllerDelegate> delegate;
@end
|
rahuljaswa/Snapp | Pod/Classes/RJLocationViewController.h | //
// RJLocationViewController.h
// Pods
//
// Created by <NAME> on 4/17/15.
//
//
#import "RJGalleryViewController.h"
#import "RJViewControllerDataSourceProtocol.h"
@class CLLocation;
@interface RJLocationViewController : RJGalleryViewController <RJViewControllerDataSourceProtocol>
- (instancetype)initWithLocation:(CLLocation *)location locationDescription:(NSString *)locationDescription;
@end
|
rahuljaswa/Snapp | Pod/Classes/RJRemoteObjectComment.h | //
// RJRemoteObjectComment.h
// Community
//
#import <Parse/Parse.h>
@class RJRemoteObjectPost;
@class RJRemoteObjectUser;
@interface RJRemoteObjectComment : PFObject <PFSubclassing>
@property (nonatomic, strong) RJRemoteObjectUser *creator;
@property (nonatomic, assign) BOOL deleted;
@property (nonatomic, strong) RJRemoteObjectPost *post;
@property (nonatomic, strong) NSString *text;
@end
|
rahuljaswa/Snapp | Pod/Classes/RJCommentsViewController.h | //
// RJCommentsViewController.h
// Community
//
#import <ChatViewControllers/RJChatTableViewController.h>
@class RJCommentsViewController;
@class RJManagedObjectUser;
@protocol RJCommentsViewControllerDelegate <NSObject>
- (void)commentsViewController:(RJCommentsViewController *)postCell didPressUser:(RJManagedObjectUser *)user;
- (void)commentsViewController:(RJCommentsViewController *)commentsViewController didPressSendButtonWithText:(NSString *)text;
@end
@class RJManagedObjectPost;
@interface RJCommentsViewController : RJChatTableViewController
@property (nonatomic, strong) NSArray *comments;
@property (nonatomic, weak) id<RJCommentsViewControllerDelegate> commentsDelegate;
@property (nonatomic, strong, readonly) RJManagedObjectPost *post;
- (instancetype)initWithPost:(RJManagedObjectPost *)post;
@end
|
rahuljaswa/Snapp | Pod/Classes/RJHomeViewController.h | <filename>Pod/Classes/RJHomeViewController.h
//
// RJHomeViewController.h
// Community
//
#import <UIKit/UIKit.h>
@class RJHomeViewController;
@protocol RJHomeViewControllerDelegate <NSObject>
- (void)homeViewController:(RJHomeViewController *)homeViewController wantsAuthenticationWithCompletion:(void (^)(BOOL success))completion;
@end
@interface RJHomeViewController : UITabBarController
@property (nonatomic, weak) id<RJHomeViewControllerDelegate> homeDelegate;
- (void)reloadWithCompletion:(void (^)(BOOL success))completion;
- (void)requestAuthenticationWithCompletion:(void (^)(BOOL success))completion;
+ (instancetype)sharedInstance;
@end
|
rahuljaswa/Snapp | Pod/Classes/RJThreadsViewController.h | <filename>Pod/Classes/RJThreadsViewController.h<gh_stars>0
//
// RJThreadsViewController.h
// Created by <NAME> on 2/28/15.
//
//
#import "RJViewControllerDataSourceProtocol.h"
#import <UIKit/UIKit.h>
@interface RJThreadsViewController : UITableViewController <RJViewControllerDataSourceProtocol>
@end
|
rahuljaswa/Snapp | Pod/Classes/RJGalleryViewController.h | <filename>Pod/Classes/RJGalleryViewController.h
//
// RJGalleryViewController.h
// Community
//
#import <UIKit/UIKit.h>
@interface RJGalleryViewController : UICollectionViewController <UICollectionViewDelegateFlowLayout>
@property (strong, nonatomic) NSArray *posts;
@end
|
rahuljaswa/Snapp | Pod/Classes/RJManagedObjectPost.h | //
// RJManagedObjectPost.h
// Community
//
#import <CoreData/CoreData.h>
#import <Foundation/Foundation.h>
@class RJManagedObjectComment;
@class RJManagedObjectFlag;
@class RJManagedObjectImage;
@class RJManagedObjectLike;
@class RJManagedObjectPostCategory;
@class RJManagedObjectThread;
@class RJManagedObjectUser;
@interface RJManagedObjectPost : NSManagedObject
@property (nonatomic, retain) NSDate *createdAt;
@property (nonatomic, retain) NSNumber *forSale;
@property (nonatomic, retain) NSNumber *latitude;
@property (nonatomic, retain) NSString *locationDescription;
@property (nonatomic, retain) NSString *longDescription;
@property (nonatomic, retain) NSNumber *longitude;
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *objectId;
@property (nonatomic, retain) NSNumber *sold;
@property (nonatomic, retain) RJManagedObjectUser *creator;
@property (nonatomic, retain) NSSet *categories;
@property (nonatomic, retain) NSSet *comments;
@property (nonatomic, retain) NSSet *flags;
@property (nonatomic, retain) NSSet *images;
@property (nonatomic, retain) NSSet *likes;
@property (nonatomic, retain) NSSet *threads;
- (NSArray *)sortedImages;
@end
@interface RJManagedObjectPost (CoreDataGeneratedAccessors)
- (void)addFlagsObject:(RJManagedObjectFlag *)value;
- (void)removeFlagsObject:(RJManagedObjectFlag *)value;
- (void)addFlags:(NSSet *)values;
- (void)removeFlags:(NSSet *)values;
- (void)addImagesObject:(RJManagedObjectImage *)value;
- (void)removeImagesObject:(RJManagedObjectImage *)value;
- (void)addImages:(NSSet *)values;
- (void)removeImages:(NSSet *)values;
- (void)addCategoriesObject:(RJManagedObjectPostCategory *)value;
- (void)removeCategoriesObject:(RJManagedObjectPostCategory *)value;
- (void)addCategories:(NSSet *)values;
- (void)removeCategories:(NSSet *)values;
- (void)addCommentsObject:(RJManagedObjectComment *)value;
- (void)removeCommentsObject:(RJManagedObjectComment *)value;
- (void)addComments:(NSSet *)values;
- (void)removeComments:(NSSet *)values;
- (void)addLikesObject:(RJManagedObjectLike *)value;
- (void)removeLikesObject:(RJManagedObjectLike *)value;
- (void)addLikes:(NSSet *)values;
- (void)removeLikes:(NSSet *)values;
- (void)addThreadsObject:(RJManagedObjectThread *)value;
- (void)removeThreadsObject:(RJManagedObjectThread *)value;
- (void)addThreads:(NSSet *)values;
- (void)removeThreads:(NSSet *)values;
@end
|
rahuljaswa/Snapp | Pod/Classes/RJRemoteObjectMessage.h | //
// RJRemoteObjectMessage.h
// Pods
//
// Created by <NAME> on 2/28/15.
//
//
#import <Parse/Parse.h>
@class RJRemoteObjectUser;
@class RJRemoteObjectThread;
@interface RJRemoteObjectMessage : PFObject <PFSubclassing>
@property (nonatomic, assign, readonly) BOOL deleted;
@property (nonatomic, strong) NSArray *readReceipts;
@property (nonatomic, strong) RJRemoteObjectUser *sender;
@property (nonatomic, strong) NSString *text;
@property (nonatomic, strong) RJRemoteObjectThread *thread;
@end
|
rahuljaswa/Snapp | Pod/Classes/RJUploadProgressCell.h | //
// RJUploadProgressView.h
// Pods
//
// Created by <NAME> on 3/21/15.
//
//
#import <UIKit/UIKit.h>
@interface RJUploadProgressCell : UITableViewCell
@property (nonatomic, strong, readonly) UIProgressView *progressView;
@end
|
rahuljaswa/Snapp | Pod/Classes/RJManagedObjectComment.h | <reponame>rahuljaswa/Snapp
//
// RJManagedObjectComment.h
// Community
//
#import <CoreData/CoreData.h>
#import <Foundation/Foundation.h>
@class RJManagedObjectPost;
@class RJManagedObjectUser;
@interface RJManagedObjectComment : NSManagedObject
@property (nonatomic, retain) NSDate *createdAt;
@property (nonatomic, retain) NSString *objectId;
@property (nonatomic, retain) NSString *text;
@property (nonatomic, retain) RJManagedObjectUser *creator;
@property (nonatomic, retain) RJManagedObjectPost *post;
@end
|
kjaylee/PutItOnMyTabBar | Example/Pods/Target Support Files/PutItOnMyTabBar/PutItOnMyTabBar-umbrella.h | #ifdef __OBJC__
#import <UIKit/UIKit.h>
#else
#ifndef FOUNDATION_EXPORT
#if defined(__cplusplus)
#define FOUNDATION_EXPORT extern "C"
#else
#define FOUNDATION_EXPORT extern
#endif
#endif
#endif
FOUNDATION_EXPORT double PutItOnMyTabBarVersionNumber;
FOUNDATION_EXPORT const unsigned char PutItOnMyTabBarVersionString[];
|
Lab-Work/IDOT-SmartWorkzone | AutoCalibration/src/others/OptQuest_autocalibration/ProblemSetup.h | <reponame>Lab-Work/IDOT-SmartWorkzone<gh_stars>1-10
#pragma once
#include "DecisionVariable.h"
#include "Constraint.h"
class ProblemSetup
{
public:
ProblemSetup(void);
~ProblemSetup(void);
// TODO: The following lists are used to track the decision variables, constraints, requirements and objectives
// that have been added to the optimization problem. These should be defined in a way that is meaningful to your
// particular implementation.
CArray<DecisionVariable, DecisionVariable&> m_decVars;
CArray<Constraint, Constraint&> m_constraints;
long m_objID;
double m_objValue;
};
|
Lab-Work/IDOT-SmartWorkzone | AutoCalibration/src/others/OptQuest_autocalibration/Constraint.h | #pragma once
class Constraint
{
public:
Constraint(void);
~Constraint(void);
// This class is used to display results at the end of the optimization.
CString m_Name;
long m_ID;
};
|
Lab-Work/IDOT-SmartWorkzone | AutoCalibration/src/others/OptQuest_autocalibration/SolutionEvaluator.h | #pragma once
#include "ProblemSetup.h"
class SolutionEvaluator
{
public:
SolutionEvaluator(void);
~SolutionEvaluator(void);
bool EvaluateOptQuestSolution(ProblemSetup* setup);
};
|
Lab-Work/IDOT-SmartWorkzone | AutoCalibration/src/others/OptQuest_autocalibration/OptQuestClient.h | <reponame>Lab-Work/IDOT-SmartWorkzone<filename>AutoCalibration/src/others/OptQuest_autocalibration/OptQuestClient.h
#pragma once
#include "DecisionVariable.h"
#include "SolutionEvaluator.h"
#include "ProblemSetup.h"
class COptQuestClient : public IOptQuestEvents
{
private:
IOptQuestPtr m_server;
bool IsOptQuestError();
long COptQuestClient::GetError();
void ThrowException();
public:
COptQuestClient(void);
~COptQuestClient(void);
bool Init();
// Optimization setup. Methods to add decision variables, constraints, requirements, and an objective
long AddContinuousVariable(CString name, double lowerBound, double upperBound);
long AddDiscreteVariable(CString name, double lowerBound, double upperBound, double stepSize);
long AddBinaryVariable(CString name);
long AddIntegerVariable(CString name, double lowerBound, double upperBound);
long AddDesignVariable(CString name, double lowerBound, double upperBound, double stepSize);
long AddPermutationVariable(CString name);
long AddUserControlledVariable(CString name);
long AddLowerRequirement(CString name, double lowerBound);
long AddUpperRequirement(CString name, double upperBound);
long AddDualRequirement(CString name, double lowerBound, double upperBound);
long AddStringConstraint(CString name, CString expression);
long AddGEConstraint(CString name, double rhs);
long AddEQConstraint(CString name, double rhs);
long AddLEConstraint(CString name, double rhs);
void AddVariableToConstraint(long constraintID, long variableID, double coeff);
bool StringConstraintHasUserVariables(long stringID);
bool StringConstraintIsLinear(long stringID);
long AddUserControlledObjective(CString name, bool setMaximize);
long AddStringObjective(CString name, CString expression, bool setMaximize);
// Solution methods. Methods to set values in a solution and methods to
// retrieve information about a solution.
void SetSolutionVariableValue(long solutionID, long variableID, double value);
double GetSolutionVariableValue(long solutionID, long variableID);
void SetSolutionObjectiveValue(long solutionID, long objID, double objValue);
double GetSolutionObjectiveValue(long solutionID, long objID);
void SetSolutionRequirementValue(long solutionID, long reqID, double value);
double GetSolutionRequirementValue(long solutionID, long reqID);
double GetSolutionConstraintLHSValue(long solutionID, long stringConstraintID);
double GetSolutionConstraintRHSValue(long solutionID, long stringConstraintID);
long GetSolutionIteration(long solutionID);
bool IsSolutionFeasible(long solutionID);
bool IsSolutionStringConstraintFeasible(long solutionID, long stringConstraintID);
bool IsSolutionRequirementFeasible(long solutionID, long reqID);
long GetBestSolution();
long GetNthBestSolution(long nth);
long GetTerminationReason();
// Optimization control
void SetLicenseID(long license);
void SetMaximumIterations(long numIterations);
void Optimize();
void StopOptimization();
void SetMaximumTime(long numSeconds);
void ContinueOptimize();
void SetAdditionalIterations(long additonalIterations);
void SetAdditionalTime(long additionalSeconds);
void OptimizeAdditional();
void SetUserControlledStop(bool onOff);
long GetElapsedTime();
void SetDatabaseSize(long numSolutions);
void SetRandomSeed(long seed);
void LogSetup(CString logFilePath);
void LogSolutions(CString logFilePath);
void UseEnglishOnly(bool onOff);
long GetNumberofCompletedIterations();
long GetNumberOfFeasibleSolutions();
long GetNumberOfInfeasibleSolutions();
void SetCannotGenerateAsTermReason(bool onOff);
long GetIterationSolution(long iteration);
void SetUseInfeasibilityIndex(bool onOff);
void CheckOptimization();
// EfficientFrontier methods
long GetNumberEfficientFrontier();
int GetNthEfficientFrontier(long nth);
bool IsNthEfficientFrontierFeasible(long nth);
// Suggested Solutions
long CreateSolution();
void AddSuggestedSolution(long solutionID);
HRESULT __stdcall QueryInterface(const IID &,void **);
ULONG __stdcall AddRef(void) { return 1; }
ULONG __stdcall Release(void) { return 1; }
HRESULT __stdcall EvaluateEvent(long solutionID);
HRESULT __stdcall MonitorStatusEvent(long solutionID);
HRESULT __stdcall EfficientFrontierEvent(long solutionID);
// ProblemSetup is a class that holds the ID's of the objects that were added to the optimization problem
ProblemSetup* setup;
SolutionEvaluator evaluator;
// When there is a com failure, retrieve the IErrorInfo.
// If it is an OptQuest error, errNumber is an OptQuest
// Exception. See documentation on COptQuestException for the meaning
// of each error.
// If it isn't and OptQuest error, errDescription will contrain the exception text
BSTR errDescription;
long errNumber;
};
|
Lab-Work/IDOT-SmartWorkzone | AutoCalibration/src/others/OptQuest_autocalibration/DecisionVariable.h | <reponame>Lab-Work/IDOT-SmartWorkzone
#pragma once
class DecisionVariable
{
public:
DecisionVariable(void);
~DecisionVariable(void);
CString m_name;
long m_ID;
// Value returned from GetSolutionVariableValue()
double m_currentValue;
// TODO: Add information that will allow you to set values in the simulation
// model for the entity that corresponds to this decsion variable. For example,
// an Excel cell reference.
};
|
taylorguo/MTCNN_Landmark106 | app/src/main/cpp/landmark106.h | //
// Created by <NAME> on 2019/6/28.
//
#pragma once
#ifndef LANDMARK106_H
#define LANDMARK106_H
#include "net.h"
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
#include <time.h>
#include <map>
using namespace std;
//struct mtcnn_point
//{
// float x;
// float y;
//};
class MTCNN{
public:
MTCNN(const string &model_path);
MTCNN(const std::vector<std::string> param_files, const std::vector<std::string> bin_files);
~MTCNN();
// Can set thread numbers for OpenMP.
// If mobile getting hotter and CPU frequency reduction, set single thread.
// Or just set multi-thread for ncnn::Extractor in inference.
void SetNumThreads(int numThreads);
void Detect(ncnn::Mat &img_, ncnn::Mat &output);
private:
ncnn::Net mtcnn_net;
ncnn::Mat img;
// Preprocess input image with pixels mean & variance
const float mean_vals[3] = {127.5, 127.5, 127.5};
const float norm_vals[3] = {0.0078125, 0.0078125, 0.0078125};
// Set number of threads for OpenMP
int num_threads =2;
};
struct Bbox
{
float score;
int x1;
int y1;
int x2;
int y2;
float area;
float ppoint[10];
float regreCoord[4];
};
class MTCNNBox {
public:
MTCNNBox(const string &model_path);
MTCNNBox(const std::vector<std::string> param_files, const std::vector<std::string> bin_files);
~MTCNNBox();
void SetMinFace(int minSize);
void SetNumThreads(int numThreads);
void SetTimeCount(int timeCount);
void detect(ncnn::Mat& img_, std::vector<Bbox>& finalBbox);
void detectMaxFace(ncnn::Mat& img_, std::vector<Bbox>& finalBbox);
// void detection(const cv::Mat& img, std::vector<cv::Rect>& rectangles);
private:
void generateBbox(ncnn::Mat score, ncnn::Mat location, vector<Bbox>& boundingBox_, float scale);
void nmsTwoBoxs(vector<Bbox> &boundingBox_, vector<Bbox> &previousBox_, const float overlap_threshold, string modelname = "Union");
void nms(vector<Bbox> &boundingBox_, const float overlap_threshold, string modelname="Union");
void refine(vector<Bbox> &vecBbox, const int &height, const int &width, bool square);
void extractMaxFace(vector<Bbox> &boundingBox_);
void PNet(float scale);
void PNet();
void RNet();
void ONet();
ncnn::Net Pnet, Rnet, Onet;
ncnn::Mat img;
const float nms_threshold[3] = {0.5f, 0.7f, 0.7f};
const float mean_vals[3] = {127.5, 127.5, 127.5};
const float norm_vals[3] = {0.0078125, 0.0078125, 0.0078125};
const int MIN_DET_SIZE = 12;
std::vector<Bbox> firstBbox_, secondBbox_,thirdBbox_;
std::vector<Bbox> firstPreviousBbox_, secondPreviousBbox_, thirdPrevioussBbox_;
int img_w, img_h;
private://部分可调参数
const float threshold[3] = { 0.8f, 0.8f, 0.6f };
int minsize = 40;
const float pre_facetor = 0.709f;
int count = 10;
int num_threads = 4;
};
#endif //LANDMARK106_H
|
MartinRohrbach/iagd | HookDll/Shared/Singleton.h | #pragma once
/// Use this macro in the header of the class you wish to make a singleton.
#define SINGLETON(classname) \
private: \
classname(); \
classname(const classname &); \
public: \
static classname & instance();
/// Use this macro in the cpp file of the class you wish to make a singleton.
#define SINGLETON_IMPL(classname) \
classname& classname::instance() \
{ \
static classname* s_instance = new classname(); \
return *s_instance; \
}
namespace Shared
{
template<typename T>
class Singleton
{
public:
/// Unique point of access
static T* Instance()
{
if (!ms_instance)
{
ms_instance = new T;
}
return ms_instance;
}
static void DestroyInstance()
{
delete ms_instance;
ms_instance = NULL;
}
private:
/// Prevent clients from creating a new singleton
Singleton()
{
}
/// Prevent clients from creating a copy of the singleton
Singleton(const Singleton<T>&)
{
}
static T* ms_instance;
};
/// Static class member initialisation.
template <typename T> T* Singleton<T>::ms_instance = NULL;
} // namespace
|
MartinRohrbach/iagd | HookDll/Shared/Thread.h | #pragma once
#define WINDOWS_LEAN_AND_MEAN
#include <windows.h>
class Thread
{
protected:
HANDLE d_threadHandle;
DWORD d_threadID;
bool d_bIsRunning;
public:
Thread();
virtual ~Thread();
void Begin();
void End();
bool IsRunning() { return d_bIsRunning; }
virtual DWORD ThreadProc();
};
|
MartinRohrbach/iagd | HookDll/Shared/TextFormat.h | <gh_stars>10-100
#ifndef TEXTFORMAT_H
#define TEXTFORMAT_H
#include <shared/UnicodeSupport.h>
class TextFormat
{
public:
TextFormat(int, char*);
~TextFormat();
// Convert a Long to a formatted Number String
std::tstring TextFormat::FormatLongToString(long l) const;
std::tstring TextFormat::FormatLongLongToString(unsigned __int64 l) const;
private:
int m_width;
char m_delimeter;
};
#endif // TEXTFORMAT_H
|
MartinRohrbach/iagd | HookDll/Shared/IDB.h | <gh_stars>10-100
#ifndef IDB_H
#define IDB_H
#include <shared/ITable.h>
namespace sqlite
{
struct IDB
{
virtual ~IDB() {}
/// Initialize the DB using the specified filename.
virtual bool Init(std::tstring const& filename) = 0;
/// Close the database.
virtual void Term() = 0;
/// Lock database for access.
//virtual void Lock() = 0;
/// Release database lock.
//virtual void UnLock() = 0;
/// Execute query and retrieve results as a table.
virtual ITablePtr ExecTable(std::wstring const& sql) const = 0;
/// Execute query and retrieve results as a table.
virtual ITablePtr ExecTable(std::string const& sql) const = 0;
/// Execute query but dot not return result. Returns false if query failed.
virtual bool Exec(std::wstring const& sql) const = 0;
/// Execute query but dot not return result. Returns false if query failed.
virtual bool Exec(std::string const& sql) const = 0;
/// Start transaction.
virtual void Begin() const = 0;
/// Complete transaction and commit changes to the DB
virtual void Commit() const = 0;
/// Abort transaction and revert changes.
virtual void Rollback() const = 0;
};
typedef boost::shared_ptr<IDB> IDBPtr;
}
#endif // IDB_H
|
MartinRohrbach/iagd | HookDll/Hook/StateRequestNpcAction.h | #pragma once
#include <windows.h>
#include <vector>
#include "DataQueue.h"
#include "BaseMethodHook.h"
#include "Vec3f.h"
/************************************************************************
/************************************************************************/
class StateRequestNpcAction : public BaseMethodHook {
public:
StateRequestNpcAction();
StateRequestNpcAction(DataQueue* dataQueue, HANDLE hEvent, char* procAddress);
void EnableHook();
void DisableHook();
private:
typedef int* (__thiscall *OriginalMethodPtr)(void*, bool, bool, Vec3f const&, void* npc);
static int m_currentPtr;
static HANDLE m_hEvent;
static DataQueue* m_dataQueue;
char* m_procAddress;
static std::vector<OriginalMethodPtr> originalMethods;
static void* __fastcall HookedMethod(void* This, bool, bool, Vec3f const& xyz, void* npc, OriginalMethodPtr original);
// TODO: Ideally this should be possible to write with generics.. but the x64 "some arguments are in registers" complicates that.
static void* __fastcall HookedMethod_Wrap0(void* This, bool a, bool b, Vec3f const& xyz, void* npc);
static void* __fastcall HookedMethod_Wrap1(void* This, bool a, bool b, Vec3f const& xyz, void* npc);
static void* __fastcall HookedMethod_Wrap2(void* This, bool a, bool b, Vec3f const& xyz, void* npc);
static void* __fastcall HookedMethod_Wrap3(void* This, bool a, bool b, Vec3f const& xyz, void* npc);
static void* __fastcall HookedMethod_Wrap4(void* This, bool a, bool b, Vec3f const& xyz, void* npc);
static void* __fastcall HookedMethod_Wrap5(void* This, bool a, bool b, Vec3f const& xyz, void* npc);
static void* __fastcall HookedMethod_Wrap6(void* This, bool a, bool b, Vec3f const& xyz, void* npc);
static void* __fastcall HookedMethod_Wrap7(void* This, bool a, bool b, Vec3f const& xyz, void* npc);
static void* __fastcall HookedMethod_Wrap8(void* This, bool a, bool b, Vec3f const& xyz, void* npc);
static void* __fastcall HookedMethod_Wrap9(void* This, bool a, bool b, Vec3f const& xyz, void* npc);
static void* __fastcall HookedMethod_Wrap10(void* This, bool a, bool b, Vec3f const& xyz, void* npc);
static void* __fastcall HookedMethod_Wrap11(void* This, bool a, bool b, Vec3f const& xyz, void* npc);
}; |
MartinRohrbach/iagd | HookDll/Hook/MessageType.h |
enum MessageType {
TYPE_OPEN_PRIVATE_STASH = 1,
TYPE_OPEN_CLOSE_TRANSFER_STASH = 2,
TYPE_REPORT_WORKER_THREAD_LAUNCHED = 3,
// Movement
TYPE_ControllerRequestNpcAction = 7,
TYPE_ControllerRequestMoveAction = 8,
TYPE_ControllerRequestRotateAction = 55,
TYPE_InventorySack_AddItem = 9,
TYPE_InventorySack_AddItem_Vec2 = 10,
TYPE_CloudGetNumFiles = 11,
TYPE_CloudRead = 12,
TYPE_CloudWrite = 13,
TYPE_DamageAttributeAbs_AddDamageToAccumulator = 14,
TYPE_Nabbed_ItemReplicaInfo = 15,
TYPE_GameEngine_GetTransferSack = 16,
TYPE_HookUnload = 17,
TYPE_GameEngine_AddItemToTransfer_01 = 18,
TYPE_GameEngine_AddItemToTransfer_02 = 19,
TYPE_GameInfo_IsHardcore = 20,
TYPE_GameInfo_SetModName = 21,
TYPE_Custom_AddItem = 22,
TYPE_Custom_AddItemFailed = 23,
TYPE_ERROR_NO_MOD_NAME = 24,
TYPE_Stash_Item_BasicInfo = 25,
TYPE_InventorySack_Sort = 26,
TYPE_Custom_AddItemSucceeded = 27,
TYPE_WorldSpawnItem = 28,
TYPE_LOG01 = 29,
TYPE_LOG02 = 30,
TYPE_HookedCombatManager_ApplyDamage = 31,
TYPE_HookedCombatManager_ApplyDamage_Exit = 32,
TYPE_LOG02_ = 33,
TYPE_DEBUG_DefenseAttribute_Jitter = 34,
TYPE_DEBUG_CharAttribute_AddJitter = 35,
TYPE_DEBUG_CharAttributeStore_Equipment_Load = 36,
TYPE_ERROR_HOOKING_PRIVATE_STASH = 37,
TYPE_ERROR_HOOKING_TRANSFER_STASH = 38,
TYPE_SAVE_TRANSFER_STASH = 39,
TYPE_ERROR_HOOKING_SAVETRANSFER_STASH = 40,
TYPE_DISPLAY_CRAFTER = 41,
TYPE_DISPLAY_CARAVAN = 42,
TYPE_DISPLAY_ENCHANTER = 43,
TYPE_ERROR_HOOKING_GENERIC = 44,
TYPE_RequestRestrictedSack = 45,
TYPE_GameInfo_IsHardcore_via_init = 47,
TYPE_GameInfo_IsHardcore_via_init_2 = 48,
TYPE_DetectedStashToLootFrom = 49,
TYPE_SaveManager = 50,
TYPE_InterceptDirectRead = 51,
TYPE_SUCCESS_HOOKING_GENERIC = 52,
TYPE_LoadPlayerTransfer = 53,
TYPE_ReadPlayerTransfer = 54,
};
|
MartinRohrbach/iagd | HookDll/Shared/SQLite.h | <filename>HookDll/Shared/SQLite.h<gh_stars>10-100
#ifndef SQLITE_H
#define SQLITE_H
#include <shared/UnicodeSupport.h>
#include <boost/smart_ptr.hpp>
#include <vector>
#include <shared/IDB.h>
// Forward declarations
struct sqlite3;
namespace sqlite
{
class Db;
class Table;
typedef boost::shared_ptr<Db> DbPtr;
typedef boost::shared_ptr<Table> TablePtr;
class Table
: public ITable
{
public:
Table(int nrow, int ncol, char **result);
//std::vector<std::string> const& Headers() const { return m_headers; }
virtual std::string Headers( unsigned int col ) const;
//std::vector<std::string> const& Data() const { return m_data; }
virtual std::string Data(unsigned int row, unsigned int col) const;
virtual size_t Columns() const;
virtual size_t Rows() const;
private:
std::vector<std::string> m_headers;
std::vector<std::string> m_data;
};
class Db
: public IDB
{
public:
struct QueryFailedException : public std::exception
{
QueryFailedException(std::tstring const& msg) : std::exception(to_ascii_copy(msg).c_str()) {}
};
Db(std::ostream &log);
virtual ~Db();
virtual bool Init(std::tstring const& filename = _T("init.db"));
virtual void Term();
virtual bool Exec(std::wstring const& sql) const;
virtual bool Exec(std::string const& sql) const;
virtual ITablePtr ExecTable(std::wstring const& sql) const;
virtual ITablePtr ExecTable(std::string const& sql) const;
virtual void Begin() const;
virtual void Commit() const;
virtual void Rollback() const;
private:
sqlite3 *m_pDb;
std::ostream &m_log;
};
} // namespace SQLite
#endif // SQLITE_H
|
MartinRohrbach/iagd | HookDll/Hook/ReadPlayerTransfer.h | #pragma once
#pragma once
#include <windows.h>
#include "DataQueue.h"
#include "BaseMethodHook.h"
class DataQueue;
/************************************************************************
/************************************************************************/
class ReadPlayerTransfer : public BaseMethodHook {
public:
ReadPlayerTransfer();
ReadPlayerTransfer(DataQueue* dataQueue, HANDLE hEvent);
void EnableHook();
void DisableHook();
private:
//bool GAME::ReadPlayerTransfer::DirectRead(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &,void * &,unsigned int &,bool,bool)
typedef int(__thiscall *OriginalMethodPtr)(void* This, void* checkedReader);
static HANDLE m_hEvent;
static OriginalMethodPtr originalMethod;
static DataQueue* m_dataQueue;
static int __fastcall HookedMethod(void* This, void* checkedReader);
};
|
MartinRohrbach/iagd | HookDll/Hook/StateRequestRotateAction.h | <filename>HookDll/Hook/StateRequestRotateAction.h
#pragma once
#include <windows.h>
#include "DataQueue.h"
#include "BaseMethodHook.h"
#include "Vec3f.h"
class StateRequestRotateAction : public BaseMethodHook {
public:
StateRequestRotateAction();
StateRequestRotateAction(DataQueue* dataQueue, HANDLE hEvent, char* procAddress);
void EnableHook();
void DisableHook();
private:
typedef int* (__thiscall *OriginalMethodPtr)(void*, Vec3f const&);
static int m_currentPtr;
static HANDLE m_hEvent;
static DataQueue* m_dataQueue;
char* m_procAddress;
static std::vector<OriginalMethodPtr> originalMethods;
static void* __fastcall HookedMethod(void* This, Vec3f const& xyz, OriginalMethodPtr original);
static void* __fastcall HookedMethod_Wrap0(void* This, Vec3f const& xyz);
static void* __fastcall HookedMethod_Wrap1(void* This, Vec3f const& xyz);
static void* __fastcall HookedMethod_Wrap2(void* This, Vec3f const& xyz);
static void* __fastcall HookedMethod_Wrap3(void* This, Vec3f const& xyz);
static void* __fastcall HookedMethod_Wrap4(void* This, Vec3f const& xyz);
static void* __fastcall HookedMethod_Wrap5(void* This, Vec3f const& xyz);
static void* __fastcall HookedMethod_Wrap6(void* This, Vec3f const& xyz);
static void* __fastcall HookedMethod_Wrap7(void* This, Vec3f const& xyz);
static void* __fastcall HookedMethod_Wrap8(void* This, Vec3f const& xyz);
static void* __fastcall HookedMethod_Wrap9(void* This, Vec3f const& xyz);
static void* __fastcall HookedMethod_Wrap10(void* This, Vec3f const& xyz);
static void* __fastcall HookedMethod_Wrap11(void* This, Vec3f const& xyz);
}; |
MartinRohrbach/iagd | injectAllTheThings-master/injectAllTheThings/fheaders.h | // Technique 1: CreateRemoteThread
DWORD demoCreateRemoteThreadW(PCWSTR pszLibFile, DWORD dwProcessId);
// Technique 2: NtCreateThreadEx
DWORD demoNtCreateThreadEx(PCWSTR pszLibFile, DWORD dwProcessId);
struct NtCreateThreadExBuffer {
ULONG Size;
ULONG Unknown1;
ULONG Unknown2;
PULONG Unknown3;
ULONG Unknown4;
ULONG Unknown5;
ULONG Unknown6;
PULONG Unknown7;
ULONG Unknown8;
};
typedef NTSTATUS(WINAPI *LPFUN_NtCreateThreadEx) (
PHANDLE hThread,
ACCESS_MASK DesiredAccess,
LPVOID ObjectAttributes,
HANDLE ProcessHandle,
LPTHREAD_START_ROUTINE lpStartAddress,
LPVOID lpParameter,
BOOL CreateSuspended,
ULONG StackZeroBits,
ULONG SizeOfStackCommit,
ULONG SizeOfStackReserve,
LPVOID lpBytesBuffer
);
// Technique 3: QueueUserAPC
DWORD demoQueueUserAPC(PCWSTR pszLibFile, DWORD dwProcessId);
// Technique 4: SetWindowsHookEx
DWORD demoSetWindowsHookEx(PCWSTR pszLibFile, DWORD dwProcessId, wchar_t *strProcName);
// Technique 5: RtlCreateUserThread
BOOL RtlCreateUserThread_Injection();
DWORD demoRtlCreateUserThread(PCWSTR pszLibFile, DWORD dwProcessId);
// Function Pointer Typedef for RtlCreateUserThread
typedef DWORD(WINAPI * pRtlCreateUserThread)(
IN HANDLE ProcessHandle,
IN PSECURITY_DESCRIPTOR SecurityDescriptor,
IN BOOL CreateSuspended,
IN ULONG StackZeroBits,
IN OUT PULONG StackReserved,
IN OUT PULONG StackCommit,
IN LPVOID StartAddress,
IN LPVOID StartParameter,
OUT HANDLE ThreadHandle,
OUT LPVOID ClientID
);
// Technique 6: thread suspend/inject/resume
#ifndef _WIN64
DWORD demoSuspendInjectResume(PCWSTR pszLibFile, DWORD dwProcessId);
#endif
DWORD demoSuspendInjectResume64(PCWSTR pszLibFile, DWORD dwProcessId);
// Technique 7: Reflective DLL Injection
DWORD demoReflectiveDllInjection(PCWSTR pszLibFile, DWORD dwProcessId);
|
MartinRohrbach/iagd | HookDll/Hook/CloudWrite.h | #pragma once
#include <windows.h>
#include "DataQueue.h"
#include "BaseMethodHook.h"
/************************************************************************
/************************************************************************/
class CloudWrite : public BaseMethodHook {
public:
CloudWrite();
CloudWrite(DataQueue* dataQueue, HANDLE hEvent);
void EnableHook();
void DisableHook();
private:
typedef bool (__thiscall *OriginalMethodPtr)(void*, void* str_filename, void const* unknown0, unsigned int unknown1, bool unknown2);
static HANDLE m_hEvent;
static OriginalMethodPtr originalMethod;
static DataQueue* m_dataQueue;
static bool __fastcall HookedMethod(void* This, void* str_filename, void const* unknown0, unsigned int unknown1, bool unknown2);
}; |
MartinRohrbach/iagd | HookDll/Hook/SaveManager.h | <gh_stars>0
#pragma once
#include <windows.h>
#include "DataQueue.h"
#include "BaseMethodHook.h"
class DataQueue;
/************************************************************************
/************************************************************************/
class SaveManager : public BaseMethodHook {
public:
SaveManager();
SaveManager(DataQueue* dataQueue, HANDLE hEvent);
void EnableHook();
void DisableHook();
private:
//bool GAME::SaveManager::DirectRead(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &,void * &,unsigned int &,bool,bool)
typedef int(__thiscall *OriginalMethodPtr)(void* This, void* filename, void const* dstBuf, unsigned int numBytesToRead, bool unknown1, bool unknown2);
static HANDLE m_hEvent;
static OriginalMethodPtr originalMethod;
static DataQueue* m_dataQueue;
static int __fastcall HookedMethod(void* This, void* filename, void const* dstBuf, unsigned int numBytesToRead, bool unknown1, bool unknown2);
};
//SAVE_MANAGER_DIRECTREAD
|
MartinRohrbach/iagd | HookDll/Hook/LoadPlayerTransfer.h | #pragma once
#pragma once
#pragma once
#include <windows.h>
#include "DataQueue.h"
#include "BaseMethodHook.h"
class DataQueue;
/************************************************************************
/************************************************************************/
class LoadPlayerTransfer : public BaseMethodHook {
public:
LoadPlayerTransfer();
LoadPlayerTransfer(DataQueue* dataQueue, HANDLE hEvent);
void EnableHook();
void DisableHook();
private:
typedef int(__thiscall *OriginalMethodPtr)(void* This);
static HANDLE m_hEvent;
static OriginalMethodPtr originalMethod;
static DataQueue* m_dataQueue;
static int __fastcall HookedMethod(void* This);
};
|
MartinRohrbach/iagd | HookDll/Hook/SaveTransferStash.h | #pragma once
#include <windows.h>
#include "DataQueue.h"
#include "BaseMethodHook.h"
class SaveTransferStash : public BaseMethodHook {
public:
SaveTransferStash();
SaveTransferStash(DataQueue* dataQueue, HANDLE hEvent);
void EnableHook();
void DisableHook();
private:
typedef void* (__thiscall *OriginalMethodPtr)(void*);
static HANDLE m_hEvent;
static OriginalMethodPtr originalMethod;
static DataQueue* m_dataQueue;
static void* privateStashSack;
static void* __fastcall HookedMethod(void* This);
}; |
MartinRohrbach/iagd | HookDll/Shared/FileUtils.h | #pragma once
#include <shared/UnicodeSupport.h>
std::tstring BrowseForFolder(HWND hWndOwner, std::tstring const& title);
std::tstring BrowseForOutputFile(HWND hWndOwner, std::tstring const& title, TCHAR* filter, std::tstring const& defaultExtension);
|
MartinRohrbach/iagd | HookDll/Hook/GetPrivateStash.h | <filename>HookDll/Hook/GetPrivateStash.h
#pragma once
#include <windows.h>
#include "DataQueue.h"
#include "BaseMethodHook.h"
/************************************************************************
Hook for the in-game "GetPrivateStash" method
Called when opening the stash
This is spammed non stop when the private stash is open (not transfer)
/************************************************************************/
class GetPrivateStash : public BaseMethodHook {
public:
GetPrivateStash();
GetPrivateStash(DataQueue* dataQueue, HANDLE hEvent);
void EnableHook();
void DisableHook();
void* GetPrivateStashInventorySack();
private:
typedef int* (__thiscall *OriginalMethodPtr)(void*);
static HANDLE m_hEvent;
static OriginalMethodPtr originalMethod;
static DataQueue* m_dataQueue;
static void* privateStashSack;
static void* __stdcall HookedMethod64(void* This);
static void* __fastcall HookedMethod(void* This, void* notUsed);
}; |
MartinRohrbach/iagd | HookDll/Hook/CloudGetNumFiles.h | <gh_stars>0
#pragma once
#include <windows.h>
#include "DataQueue.h"
#include "BaseMethodHook.h"
/************************************************************************
/************************************************************************/
class CloudGetNumFiles : public BaseMethodHook {
public:
CloudGetNumFiles();
CloudGetNumFiles(DataQueue* dataQueue, HANDLE hEvent);
void EnableHook();
void DisableHook();
private:
typedef unsigned int (__thiscall *OriginalMethodPtr)(void*);
static HANDLE m_hEvent;
static OriginalMethodPtr originalMethod;
static DataQueue* m_dataQueue;
static unsigned int __fastcall HookedMethod(void* This);
}; |
MartinRohrbach/iagd | HookDll/Shared/Mutex.h | #pragma once
class Mutex
{
HANDLE d_mutex;
public:
Mutex()
{
#if defined( _WIN32 ) && defined( _MT )
// This mutex will help the two threads share their toys.
d_mutex = CreateMutex( NULL, false, NULL );
//if( d_mutex == NULL )
// throw cError( "cMonitor::cMonitor() - Mutex creation failed." );
#endif
}
virtual ~Mutex()
{
#if defined( _WIN32 ) && defined( _MT )
if( d_mutex != NULL )
{
CloseHandle( d_mutex );
d_mutex = NULL;
}
#endif
}
void MutexOn() const
{
#if defined( _WIN32 ) && defined( _MT )
WaitForSingleObject( d_mutex, INFINITE ); // To be safe...
#endif
}
void MutexOff() const
{
#if defined( _WIN32 ) && defined( _MT )
ReleaseMutex( d_mutex ); // To be safe...
#endif
}
};
|
MartinRohrbach/iagd | HookDll/Shared/stdafx.h | <gh_stars>10-100
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#define STRICT
#define _WTL_USE_CSTRING
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#define _WIN32_WINNT 0x0501
#define WINVER 0x0501
#include <Windows.h>
#include <tchar.h>
//#include <atlbase.h> // Base ATL classes
//#include <atlapp.h>
//#include <atlwin.h> // ATL windowing classes
//#include <atlframe.h>
//#include <atlctrls.h>
//#include <atldlgs.h>
//#include <atlctrlw.h>
//#include <atlmisc.h>
//#include <atlcrack.h>
//#include <atltypes.h>
//#include <atlcoll.h>
#include <stdio.h>
#include <boost/smart_ptr.hpp>
#include <boost/lexical_cast.hpp>
|
MartinRohrbach/iagd | HookDll/Shared/UnicodeSupport.h | <gh_stars>10-100
#pragma once
#include <string>
#include <sstream>
#include <tchar.h>
#include <boost/filesystem.hpp>
#include <boost/format.hpp>
namespace std {
typedef basic_string<TCHAR> tstring;
typedef basic_stringstream<TCHAR> tstringstream;
typedef basic_ostringstream<TCHAR> tostringstream;
typedef basic_ostream<TCHAR> tostream;
typedef basic_ofstream<TCHAR> tofstream;
}
/// Typedef a character independent path class as tpath.
namespace boost { namespace filesystem {
#ifdef UNICODE
typedef wpath tpath;
#else
typedef path tpath;
#endif
}} // namespace boost::filesystem
/// Typedef a character independent format class as tformat.
namespace boost {
typedef basic_format<TCHAR> tformat;
}
std::string to_ascii_copy(std::wstring const& input);
std::string to_ascii_copy(std::string const& input);
std::string to_utf8_copy(std::tstring const& input);
std::tstring from_ascii_copy(std::string const& input);
std::tstring from_utf8_copy(std::string const& input);
#define STREAM2STR( streamdef ) \
(((std::tostringstream&)(std::tostringstream().flush() << streamdef)).str())
|
MartinRohrbach/iagd | HookDll/Shared/ITable.h | <reponame>MartinRohrbach/iagd<gh_stars>10-100
#ifndef ITABLE_H
#define ITABLE_H
namespace sqlite
{
struct ITable
{
virtual ~ITable() {}
virtual std::string Headers(unsigned int col) const = 0;
virtual std::string Data(unsigned int row, unsigned int col) const = 0;
virtual size_t Columns() const = 0;
virtual size_t Rows() const = 0;
};
typedef boost::shared_ptr<ITable> ITablePtr;
}
#endif // ITABLE_H
|
MartinRohrbach/iagd | HookDll/Hook/DataQueue.h | #ifndef DATAQUEUE_H
#define DATAQUEUE_H
#include <queue>
#include <boost/shared_ptr.hpp>
#include <boost/shared_array.hpp>
#include <boost/thread.hpp>
class DataItem
{
public:
DataItem(unsigned long _type, unsigned int _size, char* _data);
unsigned long type() const;
char* data() const;
unsigned int size() const;
private:
boost::shared_array<char> m_data;
unsigned int m_size;
unsigned long m_type;
};
typedef boost::shared_ptr<DataItem> DataItemPtr;
/**
* This is a data queue class that supports multiple threads.
*/
class DataQueue {
public:
DataQueue();
~DataQueue();
/// This pushes a copy of the specified data on the queue.
void push(DataItemPtr item);
/// This pops the front of the queue.
DataItemPtr pop();
/// Returns true if no items on queue
bool empty() const { return m_queue.empty(); }
private:
typedef std::queue<DataItemPtr> DataItemQueue;
DataItemQueue m_queue;
boost::mutex m_mutex;
//typedef std::queue<COPYDATASTRUCT*> COPYDATASTRUCTQUEUE;
//COPYDATASTRUCTQUEUE g_dataQueue;
};
#endif // DATAQUEUE_H
|
MartinRohrbach/iagd | HookDll/Hook/Vec3f.h | <reponame>MartinRohrbach/iagd
#pragma once
// Definition found in Engine.dll
struct Vec3f {
// We want bytes 8-20, ignoring the first 4, keeping 4-8 as a sector Id
float unknown2, unknown, x, y, z;
};
|
kaykay38/dwm | keybindings.h | <reponame>kaykay38/dwm
/* KEY BINDINGS */
#include <X11/XF86keysym.h>
/* helper for spawning shell commands in the pre dwm-5.0 fashion */
#define SHCMD(cmd) { .v = (const char*[]){ "/bin/sh", "-c", cmd, NULL } }
/* commands */
static char dmenumon[2] = "0"; /* component of dmenucmd, manipulated in spawn() */
static const char *dmenucmd[] = { "dmenu_run", "-m", dmenumon, "-fn", dmenufont, "-nb", col_gray1, "-nf", col_gray3, "-sb", col_gray0, "-sf", col_gray4, NULL };
static const char *termcmd[] = { "/usr/bin/alacritty", NULL };
static const char *termTabbedCMD[] = { "tabbed","-c","-r","2","alacritty","--embed","\"\"", NULL };
static const char *termAltCMD[] = { "/usr/bin/kitty", NULL };
static const char *rofiCMD[] = { "rofi", "-no-lazy-grab", "-show", "drun", "-modi", "drun", "-theme", "/home/mia/.config/rofi/config.rasi", NULL };
static const char *rofiLaunchpadCMD[] = { "rofi", " -no-lazy-grab", "-normal-window", "-modi", "drun", "-show", "drun", "-theme ", "/home/mia/.config/rofi/themes/launchpad.rasi", NULL };
static const char *rofiRunCMD[] = { "rofi", "-no-lazy-grab", "-show", "run", "-modi", "run", "-theme", "/home/mia/.config/rofi/text.rasi", NULL };
static const char *rofiWindowCMD[] = { "rofi", "-no-lazy-grab", "-modi", "window", "-show", "window", "-show-icons", "-theme", "/home/mia/.config/rofi/config.rasi", NULL };
// static const char *rofiGreenclipCMD[] = { "rofi", "-no-lazy-grab", "-modi", "'CLIPBOARD:greenclip print'", "-show", "CLIPBOARD", "-run-command", "'{cmd}'", "-theme", "/home/mia/.config/rofi/text.rasi", NULL };
static const char *browserCMD[] = { "/usr/bin/brave", "%U", NULL };
static const char *youtubeCMD[] = { "/usr/bin/brave", "https://www.youtube.com", NULL };
static const char *fileExplorerCMD[] = { "/usr/bin/pcmanfm", NULL };
static const char *pavucontrolCMD[] = { "/usr/bin/pavucontrol", NULL };
static const char *spotifyCMD[] = { "spotify", NULL };
static const char *playerctlInfoCMD[] = { "/usr/local/bin/playerctl-info", NULL };
static const char *discordCMD[] = { "/usr/bin/discord", NULL };
static const char *zoomCMD[] = { "/usr/bin/zoom", NULL };
static const char *fullScreenshotCMD[] = { "/home/mia/.config/.system/fullScreenshot.sh", NULL };
static const char *curWindowScreenshotCMD[] = { "/home/mia/.config/.system/curWindowScreenshot.sh", NULL };
/* static const char *selectionScreenshotCMD[] = { "/home/mia/.config/.system/selectionScreenshot.sh", NULL }; */
/* static const char *todoListCMD[] = { "kitty","-e","/home/mia/OneDrive/CodeWorkspace/Scripts/todo", NULL }; */
static const char *canvasCMD[] = { "/usr/bin/brave", "https://canvas.ewu.edu/", NULL};
// static const char *dualMonitorCMD[] = { "dual-vertical-left-monitor", NULL };
static const char *dualMonitorCMD[] = { "dual-horizontal-left-monitor", NULL };
/* key definitions */
#define ALT Mod1Mask // Mod1Mask=ALT DEFAULT SETTING
#define MODKEY Mod4Mask // Mod4Mask=Windows/Super key
// MOD = Super/Windows Key
#define TAGKEYS(KEY,TAG) \
{ MODKEY, KEY, view, {.ui = 1 << TAG} }, \
{ MODKEY|ControlMask, KEY, toggleview, {.ui = 1 << TAG} }, \
{ MODKEY|ShiftMask, KEY, tag, {.ui = 1 << TAG} }, \
{ MODKEY|ControlMask|ShiftMask, KEY, toggletag, {.ui = 1 << TAG} },
static Key keys[] = {
/* modifier key function argument */
{ MODKEY, XK_s, spawn, SHCMD("/usr/local/bin/dwmkeybindings")},
//utility, MOD + s, show dwm key bindings
{ MODKEY, XK_Return, spawn, {.v = termTabbedCMD } },
//utility, MOD + Enter, Alacritty tabbed
{ MODKEY|ControlMask, XK_Return, spawn, {.v = termcmd } },
//utility, MOD + Control + Enter, Alacritty terminal
{ MODKEY|ControlMask|ShiftMask, XK_Return, spawn, {.v = termAltCMD } },
//utility, MOD + Control + Shift + Enter, Kitty terminal
{ MODKEY|ALT, XK_space, spawn, {.v = browserCMD } },
//app, MOD + Alt + Space, Brave browser
{ MODKEY|Mod1Mask, XK_p, spawn, {.v = dmenucmd } },
//utility, MOD + Alt + p, dmenu run
{ ALT, XK_space, spawn, {.v = rofiCMD } },
//utility, Alt + Space, Rofi drun
{ MODKEY|ControlMask, XK_space, spawn, {.v = rofiLaunchpadCMD } },
//utility, Alt + Control, Rofi launchpad
{ MODKEY, XK_r, spawn, {.v = rofiRunCMD } },
//utility, MOD + r, Rofi run
{ MODKEY, XK_w, spawn, {.v = rofiWindowCMD } },
//utility, MOD + w, Rofi windows
{ MODKEY, XK_slash, spawn, SHCMD("/usr/local/bin/dictation-toggle") },
//utility, MOD + /, dictation toggle
{ MODKEY, XK_y, spawn, SHCMD("/usr/local/bin/rofiemoji") },
//utility, MOD + y, Rofi emoji selector
{ MODKEY|ALT, XK_Return, spawn, {.v = canvasCMD } },
//app, MOD + Alt + Enter, Canvas
{ MODKEY|ALT, XK_s, spawn, {.v = spotifyCMD } },
//music, MOD + Alt + s, Spotify
{ MODKEY, XK_p, spawn, SHCMD("/usr/local/bin/mpvplaylist") },
//music, MOD + p, music/video playlists (Rofi,mpv)
{ MODKEY|ShiftMask, XK_s, spawn, {.v = playerctlInfoCMD } },
//music, MOD + Shift + s, Playterctl info
{ MODKEY, XK_v, spawn, SHCMD("rofi -no-lazy-grab -modi 'CLIPBOARD:greenclip print' -show CLIPBOARD -run-command '{cmd}' -theme ~/.config/rofi/text.rasi") },
//utility, MOD + v, Greenclip clipboard
{ MODKEY, XK_z, spawn, {.v = zoomCMD } },
//app, MOD + z, Zoom Video Conferencing
{ MODKEY, XK_F1, spawn, {.v = youtubeCMD } },
//app, MOD + F1, Youtube
{ MODKEY, XK_F2, spawn, {.v = fileExplorerCMD } },
//app, MOD + F2, Pcmanfm file browser
{ MODKEY, XK_F3, spawn, SHCMD("/home/mia/Security/autovpn") },
//system, MOD + F3, EWU VPN
{ MODKEY, XK_F4, spawn, {.v = discordCMD } },
//app, MOD + F4, Discord
{ MODKEY|ShiftMask, XK_d, spawn, {.v = dualMonitorCMD } },
//system, MOD + Shift + d, dual vertical monitor toggle
{ MODKEY|ShiftMask, XK_m, spawn, {.v = pavucontrolCMD } },
//utility, MOD + Shift + m, Pavucontrol
{ MODKEY, XK_u, spawn, SHCMD("dmenumount") },
//utility, MOD + u, Mount Drives (dmenu)
{ MODKEY|ShiftMask, XK_u, spawn, SHCMD("dmenuumount") },
//utility, MOD + Shift + u, Unmount Drives (dmenu)
{ 0, XK_Print, spawn, {.v = fullScreenshotCMD } },
//utility, Print, screenshot full screen
{ MODKEY, XK_Print, spawn, {.v = curWindowScreenshotCMD } },
//utility, MOD + Print, screenshot window
{ MODKEY|ShiftMask, XK_Print, spawn, SHCMD("flameshot gui") },
//utility, MOD + Shift + Print, screenshot selection (Flameshot)
{ ALT, XK_Print, spawn, SHCMD("killall -9 '/usr/bin/flameshot' && notify-send 'Flameshot' 'Quit Successfuly'") },
//utility, Alt + Print, quit Flameshot
{ MODKEY|ControlMask|ALT, XK_space, spawn, SHCMD("skippy-xd") },
//system, MOD + Control + Alt + Space, dashboard view
{ 0, XF86XK_AudioNext, spawn, SHCMD("playerctl --player=spotify,spotifyd,mpv,%any next") },
//function, XF86XK_AudioNext, Playerctl next
{ 0, XF86XK_AudioPrev, spawn, SHCMD("playerctl --player=spotify,spotifyd,mpv,%any previous") },
//function, XF86XK_AudioPrev, Playerctl previous
{ 0, XF86XK_AudioPlay, spawn, SHCMD("playerctl --player=spotify,spotifyd,mpv,%any play-pause") },
//function, XF86XK_AudioPlay, play/pause
{ 0, XF86XK_AudioLowerVolume, spawn, SHCMD("volume-down") },
//function, XF86XK_AudioLowerVolume, decrease volume
{ 0, XF86XK_AudioRaiseVolume, spawn, SHCMD("volume-up") },
//function, XF86XK_AudioRaiseVolume, increase volume
{ 0, XF86XK_AudioMute, spawn, SHCMD("volume-mute") },
//function, XF86XK_AudioMute, mute/unmute
{ 0, XF86XK_PowerOff, spawn, SHCMD("/home/mia/.config/rofi/powermenu/powermenu.sh") },
//function, XF86XK_PowerOff, power menu
{ MODKEY, XK_b, togglebar, {0} },
//appearance, MOD + b, toggle bar
{ MODKEY|ALT, XK_h, shiftviewtag, {.i = -1 } },
//tag, MOD + Alt + h, next tag
{ MODKEY|ALT, XK_l, shiftviewtag, {.i = +1 } },
//tag, MOD + Alt + l, previous tag
/* { MODKEY, XK_j, focusstack, {.i = +1 } }, */
/* //window, MOD + j, focus next visible window */
/* { MODKEY, XK_k, focusstack, {.i = -1 } }, */
/* //window, MOD + k, focus previous visible window */
{ MODKEY, XK_j, focusstackvis, {.i = +1 } },
//window, MOD + j, focus next visible window
{ MODKEY, XK_k, focusstackvis, {.i = -1 } },
//window, MOD + k, focus previous visible window
{ MODKEY|ALT, XK_j, focusstackhid, {.i = +1 } },
//window, MOD + Alt + j, focus next hidden window
{ MODKEY|ALT, XK_k, focusstackhid, {.i = -1 } },
//window, MOD + Alt + k, focus previous hidden window
{ MODKEY|ShiftMask, XK_n, show, {0} },
//window, MOD + Shift + n, show hidden window
{ MODKEY, XK_n, hide, {0} },
//window, MOD + n, hidden window
{ MODKEY|ShiftMask, XK_j, movestack, {.i = +1 } },
//window, MOD + Shift + j, move window up stack
{ MODKEY|ShiftMask, XK_k, movestack, {.i = -1 } },
//window, MOD + Shift + k, move window down stack
{ MODKEY, XK_i, incnmaster, {.i = +1 } },
//layout, MOD + i, increase master stack
{ MODKEY, XK_d, incnmaster, {.i = -1 } },
//layout, MOD + d, decrease master stack
{ MODKEY, XK_h, setmfact, {.f = -0.05} },
//window, MOD + h, decrease window width
{ MODKEY, XK_l, setmfact, {.f = +0.05} },
//window, MOD + l, increase window width
{ MODKEY|ShiftMask, XK_Return, zoom, {0} },
//window, MOD + Shift + Enter, move to master stack
{ MODKEY, XK_Tab, view, {0} },
//tag, MOD + Tab, go to previously navigated tag
{ MODKEY|ShiftMask, XK_q, killclient, {0} },
//window, MOD + Shift + q, kill window
{ MODKEY, XK_t, setlayout, {.v = &layouts[0]} },
//layout, MOD + t, tiling master/stack layout
{ MODKEY, XK_f, setlayout, {.v = &layouts[1]} },
//layout, MOD + f, floating layout
{ MODKEY, XK_m, setlayout, {.v = &layouts[2]} },
//layout, MOD + m, monocle layout
{ MODKEY, XK_g, setlayout, {.v = &layouts[3]} },
//layout, MOD + g, grid layout
{ MODKEY, XK_space, setlayout, {0} },
//layout, MOD + Space, toggle between most recently used two layouts
{ MODKEY|ALT, XK_comma, cyclelayout, {.i = -1 } },
//layout, MOD + Alt + , , cycle layouts previous
{ MODKEY|ALT, XK_period, cyclelayout, {.i = +1 } },
//layout, MOD + Alt + . , cycle layouts next
{ MODKEY|ShiftMask, XK_f, togglefullscr, {0} },
//window, MOD + Shift + f, toggle fullscreen
{ MODKEY|ShiftMask, XK_space, togglefloating, {0} },
//window, MOD + Shift + Space, toggle floating
{ MODKEY, XK_0, view, {.ui = ~0 } },
//window, MOD + 0, view
/* { MODKEY|ShiftMask, XK_0, tag, {.ui = ~0 } }, */
/* //window, MOD + Shift + 0, show on every tag */
{ MODKEY|ShiftMask, XK_0, toggletag, {.ui = ~0 } },
//window, MOD + Shift + 0, toggle show on every tag
{ MODKEY, XK_comma, focusmon, {.i = -1 } },
//screen, MOD + , , focus previous monitor
{ MODKEY, XK_period, focusmon, {.i = +1 } },
//screen, MOD + . , focus next monitor
{ MODKEY|ShiftMask, XK_comma, tagmon, {.i = -1 } },
//window, MOD + Shift + , , move window to previous monitor
{ MODKEY|ShiftMask, XK_period, tagmon, {.i = +1 } },
//window, MOD + Shift + . , move window to next monitor
{ MODKEY, XK_minus, setgaps, {.i = -1 } },
//gap, MOD + -, decrease gap
{ MODKEY, XK_equal, setgaps, {.i = +1 } },
//gap, MOD + =, increase gaps
{ MODKEY|ShiftMask, XK_minus, setgaps, {.i = 0 } },
//gap, MOD + Shift + -, remove gaps
TAGKEYS( XK_1, 0)
//tag, MOD + 1, tag 1
TAGKEYS( XK_2, 1)
//tag, MOD + 2, tag 2
TAGKEYS( XK_3, 2)
//tag, MOD + 3, tag 3
TAGKEYS( XK_4, 3)
//tag, MOD + 4, tag 4
TAGKEYS( XK_5, 4)
//tag, MOD + 5, tag 5
TAGKEYS( XK_6, 5)
//tag, MOD + 6, tag 6
TAGKEYS( XK_7, 6)
//tag, MOD + 7, tag 7
TAGKEYS( XK_8, 7)
//tag, MOD + 8, tag 8
/*TAGKEYS( XK_9, 8)*/
{ MODKEY|ShiftMask, XK_Escape, spawn, SHCMD("/home/mia/.config/rofi/powermenu/powermenu.sh") },
//system, MOD + Shift + Escape, power menu
{ MODKEY|ShiftMask, XK_r, quit, {1} },
//system, MOD + Shift + r, restart dwm
/* { ControlMask|ShiftMask, XK_Escape, quit, {0} }, */
/* //system, Control + Shift + Escape, logout/quit dwm */
};
/* button definitions */
/* click can be ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle, ClkClientWin, or ClkRootWin */
static Button buttons[] = {
/* click event mask button function argument */
{ ClkLtSymbol, 0, Button1, setlayout, {0} },
{ ClkLtSymbol, 0, Button3, setlayout, {.v = &layouts[2]} },
{ ClkWinTitle, 0, Button2, zoom, {0} },
{ ClkWinTitle, 0, Button1, togglewin, {0} },
{ ClkWinTitle, 0, Button3, killclient, {0} },
{ ClkStatusText, 0, Button2, spawn, {.v = termcmd } },
{ ClkClientWin, MODKEY, Button1, movemouse, {0} },
{ ClkClientWin, MODKEY, Button2, togglefloating, {0} },
{ ClkClientWin, MODKEY, Button3, resizemouse, {0} },
{ ClkTagBar, 0, Button1, view, {0} },
{ ClkTagBar, 0, Button3, toggleview, {0} },
{ ClkTagBar, MODKEY, Button1, tag, {0} },
{ ClkTagBar, MODKEY, Button3, toggletag, {0} },
};
|
ElyTgy/htopReplica_0 | include/processor.h | #ifndef PROCESSOR_H
#define PROCESSOR_H
#include "linux_parser.h"
struct ProcessorBase {
public:
float Utilization();
virtual long GetActiveJiffies()=0;
protected:
long _prevIdle=0;
long _idle=0;
long _prevActive=0;
long _active=0;
long _prevTotal=0;
long _total=0;
const float epsilon = 0.0001f;
};
class CPUProccessor : public ProcessorBase
{
//currently only calculates the aggregate cpu's utilization
public:
CPUProccessor(int cpuNum=-1); //-1 means aggregate cpu proccess
long GetActiveJiffies() override;
private:
const int _cpuNum;
};
class ProccessProccessor : public ProcessorBase
{
public:
ProccessProccessor(int pid);
long GetActiveJiffies() override;
private:
const int _processNum;
};
#endif
|
clegaard/metrixplusplus | src/mpp/tests/general/test_std_suppress/sources/test.c | <reponame>clegaard/metrixplusplus
/* comment here per global region
*
* metrix++: suppress std.code.length:total
* metrix++: suppress std.general:size
* metrix++: suppress std.general:size intentional duplicate
*/
/*metrix++: suppress std.code.length:total*/
int func()
{
/* comment here */
}
int func2()
{
/*metrix++: suppress std.code.length:total*/
}
/* metrix++: suppress std.code.length:total */
int func3()
{
/* metrix++: suppress std.code.length:total*/
}
/* bla-bla */
/* metrix++: suppress std.code.length:total */
/* bla-bla */
int func4()
{
/* metrix++: suppress std.code.length:total*/
}
/* metrix++: suppress std.code.length:total */
struct cl1
{
};
struct cl2
{
/* metrix++: suppress std.code.length:total*/
};
// bla-bla
//metrix++: suppress std.code.length:total
// bla-bla
struct cl3
{
};
/* bla-bla-bla */
struct no_suppress_cl
{
};
/* bla-bla-bla */
int nu_suppress_func()
{
/* bla-bla-bla */
}
struct cl2
{
/* metrix++: suppress std.code.length:total per class */
/* metrix++: suppress std.code.length:total per function */
int func4()
{
}
int func_no_suppress_within_struct()
{
}
};
/* metrix++: suppress invalid:metric */
struct suppresed_for_invalid_metric
{
};
/* metrix++: suppress std.code.length:invlaid_metric */
struct suppresed_for_invalid_metric
{
};
/* metrix++: suppress invalid:metric */
/* metrix++: suppress std.code.length:total */
struct suppressed_for_size_and_invalid_metric
{
};
/* metrix++: suppress invalid:metric */
/* metrix++: suppress std.code.length:total */
/* metrix++: suppress std.code.complexity:cyclomatic */
int suppressed_for_size_and_complexity_and_invalid_metric()
{
if (1) return;
}
// metrix++: suppress std.code.length:total asdas
// metrix++: suppress std.code.complexity:cyclomatic adsad
int func7()
{
if (1) return;
}
// metrix++: suppress std.code.complexity:cyclomatic adsad
int nu_suppress_for_size()
{
if (1) return;
}
// metrix++: suppress std.code.length:total adsad
int no_suppress_for_cyclomatic_complexity()
{
if (1) return;
}
// metrix++: suppress std.code.length:total long-long
// description why it was suppressed
// metrix++: suppress std.code.complexity:cyclomatic
int func8()
{
if (1) return;
}
/* metrix++: suppress std.code.length:total long-long */
/* description why it was suppressed */
/* metrix++: suppress std.code.complexity:cyclomatic */
int func9()
{
if (1) return;
}
// metrix++: suppress std.code.complexity:cyclomatic adsad
int bad_suppress_for_size()
{
// metrix++: suppress std.code.length:total
if (1) return;
}
/* metrix++: suppress std.code.length:total long-long
* description why it was suppressed
* metrix++: suppress std.code.complexity:cyclomatic */
int func10()
{
if (1) return;
}
/* metrix++: suppress std.code.length:total
* metrix++: suppress std.code.length:total */
int duplicate_suppression_of_size()
{
}
/* metrix++: suppress std.general:size intentional suppression per file metric
* metrix++: suppress std.code.length:total */
int bad_suppression_of_file_size()
{
}
|
brenoalef/flex_bison_compiler | symbol_table.h | <filename>symbol_table.h
struct symrec {
char *name;
int offset;
struct symrec *next;
};
typedef struct symrec symrec;
struct element {
char el_type;
int int_val;
char *string_val;
char bool_val;
};
typedef struct element element;
symrec *identifier;
symrec *sym_table = (symrec *) 0;
symrec *putsym(char *sym_name) {
symrec *ptr;
ptr = (symrec *) malloc(sizeof(symrec));
ptr->name = (char *) malloc(strlen(sym_name) + 1);
strcpy(ptr->name, sym_name);
ptr->offset = data_location();
ptr->next = (struct symrec *) sym_table;
sym_table = ptr;
return ptr;
}
symrec *getsym(char *sym_name) {
symrec *ptr;
for (ptr = sym_table; ptr != (symrec *) 0; ptr = (symrec *) ptr->next) {
if (strcmp(ptr->name, sym_name) == 0) {
return ptr;
}
}
return 0;
}
|
brenoalef/flex_bison_compiler | stack_machine.h | <gh_stars>0
enum code_ops {
HALT, STORE, JMP_FALSE, GOTO,
DATA, LD_CONST, LD_VAR,
READ_VAL, WRITE_VAL,
LT, LEQU, EQU, GEQU, GT, NEQU,
NOT_OP, AND_OP, OR_OP,
ADD, SUB, NEG, MULT, DIV
};
char *op_name[] = {
"halt", "store", "jmp_false", "goto",
"data", "ld_const", "ld_var",
"in_val", "out_val",
"lt", "lequ", "equ", "gequ", "gt", "nequ",
"not_op", "and_op", "or_op",
"add", "sub", "neg", "mult", "div"
};
struct instruction {
enum code_ops op;
element *arg;
};
struct instruction code[999];
element stack[999];
int pc = 0;
struct instruction ir;
int ar = 0;
int top = 0;
char ch;
void check_type(element *val1, element *val2, char type) {
if (val1->el_type != type || (val2 != NULL && val2->el_type != type)) {
yyerror("Tipo incompativel");
}
}
void fetch_execute_cycle() {
do {
ir = code[pc++];
switch (ir.op) {
case HALT:
printf("halt\n");
break;
case READ_VAL:
printf("Input: ");
int arg = ir.arg->int_val;
switch (stack[ar + arg].el_type) {
case 'i':
scanf("%d", &stack[ar + arg].int_val);
break;
case 'b':
scanf("%c", &stack[ar + arg].bool_val);
stack[ar + arg].bool_val = stack[ar + arg].bool_val == 0 ? 0 : 1;
break;
case 's':
scanf("%s", stack[ar + arg].string_val);
break;
}
break;
case WRITE_VAL:
switch(stack[top].el_type) {
case 'i':
printf("%d\n", stack[top--].int_val);
break;
case 'b':
printf("%d\n", stack[top--].bool_val);
break;
case 's':
printf("%s\n", stack[top--].string_val);
break;
}
break;
case STORE:
stack[ir.arg->int_val] = stack[top--];
break;
case JMP_FALSE:
if (stack[top--].bool_val == 0) {
pc = ir.arg->int_val;
}
break;
case GOTO:
pc = ir.arg->int_val;
break;
case DATA:
top = top + ir.arg->int_val;
break;
case LD_CONST:
stack[++top] = *ir.arg;
break;
case LD_VAR:
stack[++top] = stack[ar + ir.arg->int_val];
break;
case LT:
check_type(&stack[top - 1], &stack[top], 'i');
stack[top - 1].el_type = 'b';
if (stack[top - 1].int_val < stack[top].int_val) {
stack[--top].bool_val = 1;
} else {
stack[--top].bool_val = 0;
}
break;
case LEQU:
check_type(&stack[top - 1], &stack[top], 'i');
stack[top - 1].el_type = 'b';
if (stack[top - 1].int_val <= stack[top].int_val) {
stack[--top].bool_val = 1;
} else {
stack[--top].bool_val = 0;
}
break;
case EQU:
check_type(&stack[top - 1], &stack[top], 'i');
stack[top - 1].el_type = 'b';
if (stack[top - 1].int_val == stack[top].int_val) {
stack[--top].bool_val = 1;
} else {
stack[--top].bool_val = 0;
}
break;
case GEQU:
check_type(&stack[top - 1], &stack[top], 'i');
stack[top - 1].el_type = 'b';
if (stack[top - 1].int_val >= stack[top].int_val) {
stack[--top].bool_val = 1;
} else {
stack[--top].bool_val = 0;
}
break;
case GT:
check_type(&stack[top - 1], &stack[top], 'i');
stack[top - 1].el_type = 'b';
if (stack[top - 1].int_val > stack[top].int_val) {
stack[--top].bool_val = 1;
} else {
stack[--top].bool_val = 0;
}
break;
case NEQU:
check_type(&stack[top - 1], &stack[top], 'i');
stack[top - 1].el_type = 'b';
if (stack[top - 1].int_val != stack[top].int_val) {
stack[--top].bool_val = 1;
} else {
stack[--top].bool_val = 0;
}
break;
case NOT_OP:
check_type(&stack[top], NULL, 'b');
stack[top].bool_val = !stack[top].bool_val;
break;
case AND_OP:
check_type(&stack[top - 1], &stack[top], 'b');
if (stack[top - 1].bool_val && stack[top].bool_val) {
stack[--top].bool_val = 1;
} else {
stack[--top].bool_val = 0;
}
break;
case OR_OP:
check_type(&stack[top - 1], &stack[top], 'b');
if (stack[top - 1].bool_val || stack[top].bool_val) {
stack[--top].bool_val = 1;
} else {
stack[--top].bool_val = 0;
}
break;
case ADD:
check_type(&stack[top - 1], &stack[top], 'i');
stack[top - 1].int_val = stack[top - 1].int_val + stack[top].int_val;
top--;
break;
case SUB:
check_type(&stack[top - 1], &stack[top], 'i');
stack[top - 1].int_val = stack[top - 1].int_val - stack[top].int_val;
top--;
break;
case NEG:
check_type(&stack[top], NULL, 'i');
stack[top].int_val = - stack[top].int_val;
break;
case MULT:
check_type(&stack[top - 1], &stack[top], 'i');
stack[top - 1].int_val = stack[top - 1].int_val * stack[top].int_val;
top--;
break;
case DIV:
check_type(&stack[top - 1], &stack[top], 'i');
stack[top - 1].int_val = stack[top - 1].int_val / stack[top].int_val;
top--;
break;
default:
printf("Internal Error: Memory Dump\n");
break;
}
} while (ir.op != HALT);
}
|
brenoalef/flex_bison_compiler | code_generator.h | <gh_stars>0
int data_offset = 0;
void set_type(char type, int offset) {
stack[offset].el_type = type;
}
int data_location() {
return data_offset++;
}
int code_offset = 0;
int gen_label() {
return code_offset;
}
int reserve_loc() {
return code_offset++;
}
void gen_code(enum code_ops operation, element * arg) {
code[code_offset].op = operation;
code[code_offset++].arg = arg;
}
void back_patch(int addr, enum code_ops operation, int arg) {
code[addr].op = operation;
element * val = (element *) malloc(sizeof(element));
val->int_val = arg;
code[addr].arg = val;
}
void print_code() {
int i = 0;
while(i < code_offset) {
printf("%3d: %-10s%4ld\n", i, op_name[(int) code[i].op], code[i].arg->int_val);
i++;
}
}
|
andwn/DoukutsuEdit | Preferences.h | #ifndef STAGE9_PREFERENCES_H
#define STAGE9_PREFERENCES_H
enum {
EDIT_PENCIL, EDIT_ERASER, EDIT_ENTITY
};
class Preferences {
public:
static Preferences& Instance() {
static Preferences instance;
return instance;
}
Preferences(Preferences const&) = delete;
void operator=(Preferences const&) = delete;
void ResetToDefault();
void Load();
void Save();
void AddRecentPXM(std::string fn);
void AddRecentTS(std::string fn);
int backGraphic;
float backColor[4];
//bool autoPXE, autoTSC, autoPXA;
std::string recentPXM[10], recentTS[10];
std::string npcListPath;
// Editor State
int editMode;
int mapZoom;
bool showGrid;
private:
Preferences();
std::string savePath;
};
#endif //STAGE9_PREFERENCES_H
|
andwn/DoukutsuEdit | PXE.h | <reponame>andwn/DoukutsuEdit<gh_stars>0
#ifndef STAGE9_PXE_H
#define STAGE9_PXE_H
typedef struct {
uint16_t x, y, id, event, type, flags;
} Entity;
class PXE {
public:
PXE() {
entities = NULL;
Clear();
}
~PXE() { free(entities); }
uint16_t Size() const { return size; }
Entity GetEntity(uint16_t i) { return i < size ? entities[i] : Entity(); }
int FindEntity(uint16_t x, uint16_t y);
void SetEntity(uint16_t i, Entity e);
void Resize(uint16_t _size);
void AddEntity(Entity e);
void DeleteEntity(uint16_t index);
void Clear();
void Load(FILE *file);
void Save(FILE *file);
private:
uint16_t size;
Entity *entities;
};
#endif //STAGE9_PXE_H
|
andwn/DoukutsuEdit | StageWindow.h | #ifndef STAGE9_STAGEWINDOW_H
#define STAGE9_STAGEWINDOW_H
#include "pxm.h"
#include "PXE.h"
#include "History.h"
#define PXA_MAX 256
#define TSC_MAX 0x8000
typedef struct {
std::string fname;
uint32_t texture;
int tex_w, tex_h;
int frame_w, frame_h;
} NpcSprite;
extern const char *vertex_src;
extern const char *fragment_src;
extern uint32_t CompileShader(int type, const char *source);
class StageWindow {
public:
StageWindow();
~StageWindow();
bool Render();
private:
History history;
uint32_t white_tex;
uint32_t back_tex;
void SetDefaultFB();
void DrawRect(float x, float y, float w, float h, uint32_t c);
void DrawRectEx(float x, float y, float w, float h, float tx, float ty, float tw, float th, uint32_t c);
void DrawUnfilledRect(float x, float y, float w, float h, uint32_t color);
void DrawGrid(int xx, int yy);
void DrawBack(int xx, int yy);
uint32_t LoadTexture(const char *fname, int *w, int *h, bool transparent = false);
void FreeTexture(uint32_t tex);
// Map
std::string pxm_fname;
std::string pxe_fname;
std::string tsc_fname;
PXM pxm;
PXE pxe;
char tsc_text[TSC_MAX];
uint32_t map_fb, map_tex;
uint16_t lastMapW, lastMapH;
int selectedEntity;
uint16_t newEntityX, newEntityY;
bool tsc_obfuscated;
void CreateMapFB(int w, int h);
void FreeMapFB();
void SetMapFB() const;
void OpenMap(std::string fname);
void SaveMap();
void SaveScript();
// Tileset
std::string tileset_fname;
std::string pxa_fname;
uint32_t tileset_fb, tileset_tex;
uint32_t tileset_image;
int tileset_width, tileset_height;
uint8_t pxa[PXA_MAX];
uint16_t tileRange[4], selectedTile;
void CreateTilesetFB();
void FreeTilesetFB();
void SetTilesetFB() const;
void OpenTileset(std::string fname);
void SaveTileset();
// NPC List
std::vector<NpcSprite> npc_sprites;
void LoadNpcList(std::string fname);
// Shader and VAO
uint32_t vao;
uint32_t vbo;
uint32_t program;
uint32_t vertex_id;
uint32_t fragment_id;
int32_t uf_scale;
int32_t uf_offset;
uint32_t attr_pos;
uint32_t attr_uv;
uint32_t attr_color;
uint32_t CompileShader(int type, const char *source);
void InitShaders();
void FreeShaders();
};
#endif //STAGE9_STAGEWINDOW_H
|
andwn/DoukutsuEdit | History.h | #ifndef STAGE9_HISTORY_H
#define STAGE9_HISTORY_H
enum {
MAP_MOD, MAP_SIZE, ENTITY_MOD, ENTITY_ADD, ENTITY_DEL
};
typedef struct {
int action;
union {
struct { uint16_t x, y, w, h, tx, ty, *old_data; } map_mod;
struct { uint16_t old_w, old_h, new_w, new_h, *old_data; } map_size;
struct { Entity old_entity, new_entity; } entity_mod;
struct { Entity new_entity; } entity_add;
struct { Entity old_entity; uint16_t index; } entity_del;
};
} HistEntry;
class History {
public:
History();
~History();
void AddEntry(HistEntry *entry);
void Clear();
void ClearUndoList();
void ClearRedoList();
HistEntry* Undo();
HistEntry* Redo();
private:
std::list<HistEntry*> undoList;
std::list<HistEntry*> redoList;
};
#endif //STAGE9_HISTORY_H
|
andwn/DoukutsuEdit | pxm.h | <gh_stars>0
#pragma once
class PXM {
public:
PXM() : PXM(20, 15) {}
PXM(uint16_t _width, uint16_t _height) : width(_width), height(_height) {
tiles = (uint8_t*) calloc(width * height, 1);
}
~PXM() { free(tiles); }
uint16_t Width() const { return width; }
uint16_t Height() const { return height; }
uint8_t Tile(uint16_t x, uint16_t y) {
return x < width ? y < height ? tiles[x + y * width] : 0 : 0;
}
void Resize(uint16_t _width, uint16_t _height);
void SetTile(uint16_t x, uint16_t y, uint8_t tile);
void Clear();
//void Shift(int16_t x, int16_t y);
void Load(FILE *file);
void Save(FILE *file);
private:
uint16_t width, height;
uint8_t *tiles;
};
|
gitter-badger/BoAT-X-Framework | sdk/wallet/api_ethereum.c | <reponame>gitter-badger/BoAT-X-Framework<gh_stars>1-10
/******************************************************************************
* Copyright (C) 2018-2021 aitos.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/*!@brief Ethereum wallet API for BoAT IoT SDK
@file
boatethwallet.c defines the Ethereum wallet API for BoAT IoT SDK.
*/
#include "boatinternal.h"
#include "web3intf.h"
#include "boatprotocols.h"
#include "rpcintf.h"
#include "randgenerator.h"
#include "bignum.h"
#include "cJSON.h"
#if BOAT_USE_OPENSSL != 0
#include <openssl/evp.h>
#include <openssl/aes.h>
#endif
/******************************************************************************
@brief Initialize Boat Ethereum Wallet
Function: BoatEthWalletInit()
This function sets up context of Boat Ethereum Wallet based on given
configuration.
DO NOT call this function directly. Instead call BoatWalletCreate() with an Ethereum
wallet configuration like:
@verbatim
BoatEthWalletConfig eth_config = {...};\n
BSINT32 wallet_index;\n
wallet_index = BoatWalletCreate( BOAT_PROTOCOL_ETHEREUM,\n
ð_config,\n
sizeof(BoatEthWalletConfig)\n
);
@endverbatim
BoatEthWalletInit() MUST be called before any use of Boat Ethereum Wallet.
BoatEthWalletDeInit() MUST be called after use of Boat Ethereum Wallet.
@see BoatEthWalletDeInit() BoatWalletCreate()
@return
This function returns instance pointer of BoatEthWallet if initialization is successful.\n
Otherwise it returns NULL.
@param[in] config_ptr
Pointer to Ethereum wallet configuration.
@param[in] config_size
Size (in byte) of Ethereum wallet configuration.
*******************************************************************************/
BoatEthWallet * BoatEthWalletInit(const BoatEthWalletConfig *config_ptr, BUINT32 config_size)
{
BoatEthWallet *wallet_ptr;
BOAT_RESULT result;
if( config_ptr == NULL )
{
BoatLog(BOAT_LOG_NORMAL, "Argument cannot be NULL.");
return NULL;
}
if( sizeof(BoatEthWalletConfig) != config_size )
{
BoatLog(BOAT_LOG_NORMAL, "Incorrect configuration size.");
return NULL;
}
wallet_ptr = BoatMalloc(sizeof(BoatEthWallet));
if( wallet_ptr == NULL )
{
return NULL;
}
// Init Web3 interface
wallet_ptr->web3intf_context_ptr = web3_init();
if( wallet_ptr->web3intf_context_ptr == NULL )
{
BoatFree(wallet_ptr);
return NULL;
}
// Set EIP-155 Compatibility to TRUE by default
BoatEthWalletSetEIP155Comp(wallet_ptr, config_ptr->eip155_compatibility);
// Configure private key
result = BoatEthWalletSetPrivkey(wallet_ptr, config_ptr->priv_key_array);
if( result != BOAT_SUCCESS)
{
web3_deinit(wallet_ptr->web3intf_context_ptr);
BoatFree(wallet_ptr);
return NULL;
}
// Configure Chain ID
BoatEthWalletSetChainId(wallet_ptr, config_ptr->chain_id);
// Configure node URL string
wallet_ptr->network_info.node_url_ptr = NULL;
result = BoatEthWalletSetNodeUrl(wallet_ptr, config_ptr->node_url_str);
if( result != BOAT_SUCCESS)
{
web3_deinit(wallet_ptr->web3intf_context_ptr);
BoatFree(wallet_ptr);
return NULL;
}
return wallet_ptr;
}
/*!*****************************************************************************
@brief De-initialize Boat Ethereum Wallet
Function: BoatEthWalletDeInit()
This function de-initialize context of Boat Ethereum Wallet.
BoatEthWalletInit() MUST be called before any use of Boat Ethereum Wallet.
BoatEthWalletDeInit() MUST be called after use of Boat Ethereum Wallet.
@see BoatEthWalletInit()
@return This function doesn't return any thing.
@param[in] wallet_ptr
Wallet context pointer
*******************************************************************************/
void BoatEthWalletDeInit(BoatEthWallet *wallet_ptr)
{
if( wallet_ptr != NULL )
{
// Destroy private key in wallet memory
memset(wallet_ptr->account_info.priv_key_array, 0x00, 32);
if( wallet_ptr->network_info.node_url_ptr != NULL )
{
BoatFree(wallet_ptr->network_info.node_url_ptr);
wallet_ptr->network_info.node_url_ptr = NULL;
}
web3_deinit(wallet_ptr->web3intf_context_ptr);
BoatFree(wallet_ptr);
}
return;
}
/******************************************************************************
@brief Set BoatWallet: URL of blockchain node
Function: BoatEthWalletSetNodeUrl()
This function sets the URL of the blockchain node to connect to.
A URL is composed of protocol, IP address/name and port, in a form:
http://a.b.com:8545
@return
This function returns BOAT_SUCCESS if setting is successful.\n
Otherwise it returns one of the error codes.
@param[in] wallet_ptr
Wallet context pointer.
@param[in] node_url_ptr
A string indicating the URL of blockchain node to connect to.
*******************************************************************************/
BOAT_RESULT BoatEthWalletSetNodeUrl(BoatEthWallet *wallet_ptr, const BCHAR *node_url_ptr)
{
BOAT_RESULT result;
if( wallet_ptr == NULL )
{
BoatLog(BOAT_LOG_NORMAL, "Argument cannot be NULL.");
return BOAT_ERROR_INVALID_ARGUMENT;
}
// Set Node URL
if( node_url_ptr != NULL )
{
if( wallet_ptr->network_info.node_url_ptr != NULL )
{
BoatFree(wallet_ptr->network_info.node_url_ptr);
}
// +1 for NULL Terminator
wallet_ptr->network_info.node_url_ptr = BoatMalloc(strlen(node_url_ptr)+1);
if( wallet_ptr->network_info.node_url_ptr != NULL )
{
strcpy(wallet_ptr->network_info.node_url_ptr, node_url_ptr);
result = BOAT_SUCCESS;
}
else
{
BoatLog(BOAT_LOG_NORMAL, "Fail to allocate memory for Node URL string.");
result = BOAT_ERROR;
}
}
else
{
BoatLog(BOAT_LOG_NORMAL, "Argument cannot be NULL.");
result = BOAT_ERROR;
}
return result;
}
/******************************************************************************
@brief Set BoatWallet: EIP-155 Compatibility
Function: BoatEthWalletSetEIP155Comp()
This function sets if the network supports EIP-155.
If the network supports EIP-155, set it to BOAT_TRUE.
Otherwise set it to BOAT_FALSE.
@return
This function returns BOAT_SUCCESS if setting is successful.\n
Otherwise it returns one of the error codes.
@param[in] wallet_ptr
Wallet context pointer.
@param[in] eip155_compatibility
BOAT_TRUE if the network supports EIP-155. Otherwise BOAT_FALSE.
*******************************************************************************/
BOAT_RESULT BoatEthWalletSetEIP155Comp(BoatEthWallet *wallet_ptr, BUINT8 eip155_compatibility)
{
if( wallet_ptr == NULL )
{
BoatLog(BOAT_LOG_NORMAL, "Argument cannot be NULL.");
return BOAT_ERROR_INVALID_ARGUMENT;
}
// Set EIP-155 Compatibility
wallet_ptr->network_info.eip155_compatibility = eip155_compatibility;
return BOAT_SUCCESS;
}
/******************************************************************************
@brief Set BoatWallet: Chain ID
Function: BoatEthWalletSetChainId()
This function sets the chain ID of the network.
If the network supports EIP-155, chain ID is part of the transaction
message to sign.
If the network doesn't support EIP-155, chain ID is ignored.
@return
This function returns BOAT_SUCCESS if setting is successful.\n
Otherwise it returns one of the error codes.
@param[in] wallet_ptr
Wallet context pointer.
@param[in] chain_id
Chain ID of the blockchain network to use.
*******************************************************************************/
BOAT_RESULT BoatEthWalletSetChainId(BoatEthWallet *wallet_ptr, BUINT32 chain_id)
{
if( wallet_ptr == NULL )
{
BoatLog(BOAT_LOG_NORMAL, "Argument cannot be NULL.");
return BOAT_ERROR_INVALID_ARGUMENT;
}
// Set Chain ID
wallet_ptr->network_info.chain_id = chain_id;
return BOAT_SUCCESS;
}
/******************************************************************************
@brief Set BoatWallet: Private Key
Function: BoatEthWalletSetPrivkey()
This function sets the private key of the wallet account.
A private key is 256 bit. If it's treated as a UINT256 in bigendian, the
valid private key value for Ethereum is [1, n-1], where n is
0xFFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE BAAEDCE6 AF48A03B BFD25E8C D0364141.
This function will call BoatEthWalletCheckPrivkey() to check the validity of
the private key.
The public key is automatically derived from the private key and the
address of the account is calculated from the public key.
In case co-sign is used, this function set the half key shard of the
private key. The public key is calculated by co-sign algorithm with the
co-sign server.
NOTE: Be very careful to PROTECT the private key.
@see
BoatEthWalletCheckPrivkey()
@return
This function returns BOAT_SUCCESS if setting is successful.\n
Otherwise it returns one of the error codes.
@param[in] wallet_ptr
Wallet context pointer.
@param[in] priv_key_array
Private key to use.
*******************************************************************************/
BOAT_RESULT BoatEthWalletSetPrivkey(BoatEthWallet *wallet_ptr, const BUINT8 priv_key_array[32])
{
BUINT8 pub_key[65];
BUINT8 pub_key_digest[32];
BOAT_RESULT result;
if( wallet_ptr == NULL )
{
BoatLog(BOAT_LOG_NORMAL, "Argument cannot be NULL.");
return BOAT_ERROR_INVALID_ARGUMENT;
}
if( priv_key_array == NULL )
{
BoatLog(BOAT_LOG_NORMAL, "Private key cannot be NULL.");
return BOAT_ERROR_INVALID_ARGUMENT;
}
result = BoatEthWalletCheckPrivkey(priv_key_array);
if( result != BOAT_SUCCESS )
{
BoatLog(BOAT_LOG_NORMAL, "Private key is not valid.");
return BOAT_ERROR;
}
// Set private key and calculate public key as well as address
// PRIVATE KEY MUST BE SET BEFORE SETTING NONCE AND GASPRICE
memcpy(wallet_ptr->account_info.priv_key_array, priv_key_array, 32);
// Calculate address from private key;
ecdsa_get_public_key65(
&secp256k1,
wallet_ptr->account_info.priv_key_array,
pub_key);
// pub_key[] is a 65-byte array with pub_key[0] being 0x04 SECG prefix followed by 64-byte public key
// Thus skip pub_key[0]
memcpy(wallet_ptr->account_info.pub_key_array, &pub_key[1], 64);
keccak_256(&pub_key[1], 64, pub_key_digest);
memcpy(wallet_ptr->account_info.address, pub_key_digest+12, 20); // Address is the least significant 20 bytes of public key's hash
return BOAT_SUCCESS;
}
/******************************************************************************
@brief Generate Private Key
Function: BoatEthWalletGeneratePrivkey()
This function generates the private key of the wallet account and calls
BoatEthWalletSetPrivkey() to save it into wallet account.
A private key is a 256 bit random number up to a value slightly smaller than
all bits being 1. See BoatEthWalletCheckPrivkey() for the details.
In case co-sign is used, this is the half key shard.
NOTE: Be very careful to PROTECT the private key.
@see
BoatEthWalletSetPrivkey() BoatEthWalletCheckPrivkey()
@return
This function returns BOAT_SUCCESS if private key is successfully generated.\n
Otherwise it returns one of the error codes.
@param[out] priv_key_array
A 32-byte buffer to hold the generated private key.
*******************************************************************************/
BOAT_RESULT BoatEthWalletGeneratePrivkey(BOAT_OUT BUINT8 priv_key_array[32])
{
BUINT32 key_try_count;
BOAT_RESULT result;
if( priv_key_array == NULL )
{
BoatLog(BOAT_LOG_NORMAL, "Buffer to hold private key cannot be NULL.");
return BOAT_ERROR;
}
// Try at most 100 times to find a random number fits for Ethereum private key
for( key_try_count = 0; key_try_count < 100; key_try_count++ )
{
result = random_stream(priv_key_array, 32);
if( result != BOAT_SUCCESS )
{
BoatLog(BOAT_LOG_CRITICAL, "Fail to generate private key.");
break;
}
result = BoatEthWalletCheckPrivkey(priv_key_array);
if( result == BOAT_SUCCESS )
{
break;
}
}
return result;
}
/******************************************************************************
@brief Check validity of given private key
Function: BoatEthWalletCheckPrivkey()
This function checks the validity of the private key.
A private key is 256 bit. If it's treated as a UINT256 in bigendian, the
valid private key value for Ethereum is [1, n-1], where n is
0xFFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE BAAEDCE6 AF48A03B BFD25E8C D0364141
@return
This function returns BOAT_SUCCESS if the key is valid.\n
Otherwise it returns one of the error codes.
@param[in] priv_key_array
Private key to check.
*******************************************************************************/
BOAT_RESULT BoatEthWalletCheckPrivkey(const BUINT8 priv_key_array[32])
{
bignum256 priv_key_bn256;
bignum256 priv_key_max_bn256;
// Valid private key value (as a UINT256) for Ethereum is [1, n-1], where n is
// 0xFFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE BAAEDCE6 AF48A03B BFD25E8C D0364141
const BUINT32 priv_key_max_u256[8] = {0xD0364141, <KEY>, 0xAF48A03B, 0xBAAEDCE6,
0xFFFFFFFE, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF};
if( priv_key_array == NULL )
{
BoatLog(BOAT_LOG_NORMAL, "Private key cannot be NULL.");
return BOAT_ERROR_INVALID_ARGUMENT;
}
// Check whether private_key_array is in valid range
// Convert private key from UINT256 to Bignum256 format
bn_read_le(priv_key_array, &priv_key_bn256);
if( bn_is_zero(&priv_key_bn256) != 0)
{
BoatLog(BOAT_LOG_NORMAL, "Private key cannot be all zeros. Fail to set private key.");
return BOAT_ERROR;
}
// Convert priv_key_max_u256 from UINT256 to Bignum256 format
bn_read_le((const uint8_t *)priv_key_max_u256, &priv_key_max_bn256);
// Check whether priv_key_bn256 is less than priv_key_max_bn256
if( bn_is_less(&priv_key_bn256, &priv_key_max_bn256) == 0 )
{
BoatLog(BOAT_LOG_NORMAL, "Private key does not conform to Ethereum. Fail to set private key.");
return BOAT_ERROR;
}
return BOAT_SUCCESS;
}
/******************************************************************************
@brief Get Balance of the wallet account
Function: BoatEthWalletGetBalance()
This function gets the balance of the wallet account from network.
If the account is not available (i.e. the address of the wallet account
never appears as a recipient in any successful non-zero-value transaction),
the balance returned is 0. It's not possible to distinguish an unavailable
account from a zero-balance account.
@return
This function returns the complete json message of the RPC method response.\n
If any error occurs, it returns NULL.
@param[in] wallet_ptr
Wallet context pointer.
@param[in] alt_address_str
A string representing which address to get balance from.
If NULL, get balance of the wallet's owner address.\n
Otherwise, get balance of the specified altered address, in HEX format like\n
"0x19c91A4649654265823512a457D2c16981bB64F5".
*******************************************************************************/
BCHAR * BoatEthWalletGetBalance(BoatEthWallet *wallet_ptr, BCHAR *alt_address_str)
{
BUINT8 alt_address[BOAT_ETH_ADDRESS_SIZE]; // Binary altered address converted from alt_address_str
BUINT8 *address_ptr; // Point to an address in binary format, either wallet
// owner's or the one converted from alt_address_str
BCHAR address_str[43]; // Address in string format, converted from address_ptr
Param_eth_getBalance param_eth_getBalance;
BCHAR *tx_balance_str;
if( wallet_ptr == NULL )
{
BoatLog(BOAT_LOG_NORMAL, "Argument cannot be NULL.");
return NULL;
}
if( alt_address_str == NULL )
{
// Query Wallet's Owner address
// PRIVATE KEY MUST BE SET BEFORE GETTING BALANCE, BECAUSE GETTING BALANCE FROM
// NETWORK NEEDS ETHEREUM ADDRESS, WHICH IS COMPUTED FROM KEY
address_ptr = wallet_ptr->account_info.address;
}
else
{
// Query specified altered address
UtilityHex2Bin(
alt_address,
BOAT_ETH_ADDRESS_SIZE,
alt_address_str,
TRIMBIN_TRIM_NO,
BOAT_TRUE
);
address_ptr = alt_address;
}
// Get balance from network
// Return value of web3_eth_getBalance() is balance in wei
UtilityBin2Hex(
address_str,
address_ptr,
BOAT_ETH_ADDRESS_SIZE,
BIN2HEX_LEFTTRIM_UNFMTDATA,
BIN2HEX_PREFIX_0x_YES,
BOAT_FALSE
);
param_eth_getBalance.address_str = address_str;
param_eth_getBalance.block_num_str = "latest";
tx_balance_str = web3_eth_getBalance(wallet_ptr->web3intf_context_ptr,
wallet_ptr->network_info.node_url_ptr,
¶m_eth_getBalance);
if( tx_balance_str == NULL )
{
BoatLog(BOAT_LOG_NORMAL, "Fail to get balance from network.");
return NULL;
}
return tx_balance_str;
}
/*!*****************************************************************************
@brief Prase RPC method RESPONSE
This function Prase "result" segment.
If "result" object is string, this function will returns contents of "result" .
If "result" object is still json object, the parameter named "child_name" will actived,
if "child_name" object is string, this function will returns contents of "child_name";
if "child_name" object is other types, his function will prompt "un-implemention yet".
For other types of "result" this function is not support yet.
@param[in] json_string
The json to be parsed.
@param[in] child_name
if "result" item is json object, this param will actived.
@param[out] result_out
The buffer to store prase result.
Caller can allocate memory for this param, or can initial it with {NULL, 0},
this function will expand the memory if it too small to store prase result.
@return
This function returns BOAT_SUCCESS if prase successed. Otherwise
it returns an error code.
*******************************************************************************/
BOAT_RESULT BoatEthPraseRpcResponseResult( const BCHAR * json_string,
const BCHAR * child_name,
BoatFieldVariable *result_out )
{
return web3_parse_json_result(json_string, child_name, result_out);
}
/******************************************************************************
@brief Initialize Ethereum Transaction
Function: BoatEthTxInit()
This function initialize an Ethereum transaction.
@see BoatEthTxSetGasPrice() BoatEthTxSetGasLimit() BoatEthTxSetRecipient()
@return
This function returns BOAT_SUCCESS if initialization is successful.\n
Otherwise it returns one of the error codes.
@param[in] wallet_ptr
The wallet pointer that this transaction is combined with.
@param[in] tx_ptr
Pointer a transaction object.
@param[in] is_sync_tx
For a stateful transaction, specify BOAT_TRUE to wait until the transaction is mined.\n
Specifiy BOAT_FALSE to allow multiple transactions to be sent continuously in a short time.\n
For a state-less contract call, this option is ignored.
@param[in] gasprice_str
A HEX string representing the gas price (unit: wei) to be used in the transaction.\n
Set <gasprice> = NULL to obtain gas price from network.\n
BoatEthTxSetGasPrice() can later be called to modify the gas price at any\n
time before the transaction is executed.
@param[in] gaslimit_str
A HEX string representing the gas limit to be used in the transaction.\n
BoatEthTxSetGasLimit() can later be called to modify the gas limit at any\n
time before the transaction is executed.
@param[in] recipient_str
A HEX string representing the recipient address, in HEX format like\n
"0x19c91A4649654265823512a457D2c16981bB64F5".\n
BoatEthTxSetRecipient() can later be called to modify the recipient at any\n
time before the transaction is executed.
*******************************************************************************/
BOAT_RESULT BoatEthTxInit(BoatEthWallet *wallet_ptr,
BoatEthTx *tx_ptr,
BBOOL is_sync_tx,
BCHAR * gasprice_str,
BCHAR * gaslimit_str,
BCHAR *recipient_str)
{
BOAT_RESULT result;
if( wallet_ptr == NULL || tx_ptr == NULL || recipient_str == NULL)
{
BoatLog(BOAT_LOG_NORMAL, "Argument cannot be NULL.");
return BOAT_ERROR_INVALID_ARGUMENT;
}
tx_ptr->wallet_ptr = wallet_ptr;
memset(&tx_ptr->rawtx_fields, 0x00, sizeof(tx_ptr->rawtx_fields));
// Set synchronous transaction flag
tx_ptr->is_sync_tx = is_sync_tx;
// Initialize gasprice
BoatFieldMax32B gasprice;
// Either manually set the gas price or get the price from network
if( gasprice_str != NULL )
{
// Manually
gasprice.field_len =
UtilityHex2Bin(
gasprice.field,
32,
gasprice_str,
TRIMBIN_LEFTTRIM,
BOAT_TRUE
);
result = BoatEthTxSetGasPrice(tx_ptr, &gasprice);
}
else
{
// To use the price obtained from network, simply call BoatTxSetGasPrice(NULL)
result = BoatEthTxSetGasPrice(tx_ptr, NULL);
}
if( result != BOAT_SUCCESS )
{
return BOAT_ERROR;
}
// Initialize gaslimit
BoatFieldMax32B gaslimit;
gaslimit.field_len =
UtilityHex2Bin(
gaslimit.field,
32,
gaslimit_str,
TRIMBIN_LEFTTRIM,
BOAT_TRUE
);
result = BoatEthTxSetGasLimit(tx_ptr, &gaslimit);
if( result != BOAT_SUCCESS )
{
return BOAT_ERROR;
}
// Initialize recipient
BUINT8 recipient[BOAT_ETH_ADDRESS_SIZE];
BUINT32 converted_len;
converted_len = UtilityHex2Bin(
recipient,
BOAT_ETH_ADDRESS_SIZE,
recipient_str,
TRIMBIN_TRIM_NO,
BOAT_TRUE
);
if( converted_len == 0 )
{
return BOAT_ERROR;
}
result = BoatEthTxSetRecipient(tx_ptr, recipient);
if( result != BOAT_SUCCESS )
{
return BOAT_ERROR;
}
// Initialize value = 0
result = BoatEthTxSetValue(tx_ptr, NULL);
if( result != BOAT_SUCCESS )
{
return BOAT_ERROR;
}
return BOAT_SUCCESS;
}
/******************************************************************************
@brief Set Transaction Parameter: Transaction Nonce
Function: BoatEthTxSetNonce()
This function sets the nonce to the transaction count of the account
obtained from network.
This function can be called after BoatEthTxInit() has been called.
@see BoatEthTxInit()
@return
This function returns BOAT_SUCCESS if setting is successful.\n
Otherwise it returns one of the error codes.
@param[in] tx_ptr
The pointer to the transaction.
@param[in] nonce
The nonce to use in the transaction.\n
If BOAT_ETH_NONCE_AUTO (0xFFFFFFFFFFFFFFFF) is specified, the nonce is\n
obtained from network.
*******************************************************************************/
BOAT_RESULT BoatEthTxSetNonce(BoatEthTx *tx_ptr, BUINT64 nonce)
{
BCHAR account_address_str[43];
Param_eth_getTransactionCount param_eth_getTransactionCount;
BCHAR *tx_count_str;
BOAT_RESULT result = BOAT_SUCCESS;
if( tx_ptr == NULL || tx_ptr->wallet_ptr == NULL )
{
BoatLog(BOAT_LOG_NORMAL, "Arguments cannot be NULL.");
return BOAT_ERROR_INVALID_ARGUMENT;
}
// PRIVATE KEY MUST BE SET BEFORE SETTING NONCE, BECAUSE GETTING NONCE FROM
// NETWORK NEEDS ETHEREUM ADDRESS, WHICH IS COMPUTED FROM KEY
// Get transaction count from network
// Return value of web3_eth_getTransactionCount() is transaction count
UtilityBin2Hex(
account_address_str,
tx_ptr->wallet_ptr->account_info.address,
BOAT_ETH_ADDRESS_SIZE,
BIN2HEX_LEFTTRIM_UNFMTDATA,
BIN2HEX_PREFIX_0x_YES,
BOAT_FALSE
);
param_eth_getTransactionCount.address_str = account_address_str;
param_eth_getTransactionCount.block_num_str = "latest";
if (BOAT_ETH_NONCE_AUTO == nonce)
{
tx_count_str = web3_eth_getTransactionCount(tx_ptr->wallet_ptr->web3intf_context_ptr,
tx_ptr->wallet_ptr->network_info.node_url_ptr,
¶m_eth_getTransactionCount);
result = BoatEthPraseRpcResponseResult( tx_count_str, "",
&tx_ptr->wallet_ptr->web3intf_context_ptr->web3_result_string_buf);
if( result != BOAT_SUCCESS )
{
BoatLog(BOAT_LOG_CRITICAL, "Fail to get transaction count from network.");
return result;
}
// Set nonce from transaction count
tx_ptr->rawtx_fields.nonce.field_len =
UtilityHex2Bin(
tx_ptr->rawtx_fields.nonce.field,
32,
(BCHAR*)tx_ptr->wallet_ptr->web3intf_context_ptr->web3_result_string_buf.field_ptr,
TRIMBIN_LEFTTRIM,
BOAT_TRUE
);
}
else
{
tx_ptr->rawtx_fields.nonce.field_len =
UtilityUint64ToBigend(
tx_ptr->rawtx_fields.nonce.field,
nonce,
TRIMBIN_LEFTTRIM
);
}
BoatLog(BOAT_LOG_NORMAL, "tx_ptr->rawtx_fields.nonce.field_len = %d", tx_ptr->rawtx_fields.nonce.field_len);
BoatLog(BOAT_LOG_NORMAL, "tx_ptr->rawtx_fields.nonce.field = %02x%02x", tx_ptr->rawtx_fields.nonce.field[0], tx_ptr->rawtx_fields.nonce.field[1]);
return BOAT_SUCCESS;
}
/******************************************************************************
@brief Set Transaction Parameter: GasPrice
Function: BoatEthTxSetGasPrice()
This function sets the gas price of the transaction.
@return
This function returns BOAT_SUCCESS if setting is successful.\n
Otherwise it returns one of the error codes.
@param[in] tx_ptr
Pointer to the transaction structure.
@param[in] gas_price_ptr
The gas price in wei.\n
If <gas_price_ptr> is NULL, the gas price obtained from network is used.
*******************************************************************************/
BOAT_RESULT BoatEthTxSetGasPrice(BoatEthTx *tx_ptr, BoatFieldMax32B *gas_price_ptr)
{
BCHAR *gas_price_from_net_str;
BOAT_RESULT result = BOAT_SUCCESS;
if( tx_ptr == NULL || tx_ptr->wallet_ptr == NULL )
{
BoatLog(BOAT_LOG_NORMAL, "Arguments cannot be NULL.");
return BOAT_ERROR_INVALID_ARGUMENT;
}
// If gas price is specified, use it
// Otherwise use gas price obtained from network
if( gas_price_ptr != NULL )
{
memcpy(&tx_ptr->rawtx_fields.gasprice,
gas_price_ptr,
sizeof(BoatFieldMax32B));
}
else
{
// Get current gas price from network
// Return value of web3_eth_gasPrice is in wei
gas_price_from_net_str = web3_eth_gasPrice(tx_ptr->wallet_ptr->web3intf_context_ptr, tx_ptr->wallet_ptr->network_info.node_url_ptr);
result = BoatEthPraseRpcResponseResult( gas_price_from_net_str, "",
&tx_ptr->wallet_ptr->web3intf_context_ptr->web3_result_string_buf);
if( result != BOAT_SUCCESS )
{
BoatLog(BOAT_LOG_NORMAL, "Fail to get gasPrice from network.");
result = BOAT_ERROR;
}
else
{
// Set transaction gasPrice with the one got from network
tx_ptr->rawtx_fields.gasprice.field_len =
UtilityHex2Bin(
tx_ptr->rawtx_fields.gasprice.field,
32,
(BCHAR*)tx_ptr->wallet_ptr->web3intf_context_ptr->web3_result_string_buf.field_ptr,
TRIMBIN_LEFTTRIM,
BOAT_TRUE
);
BoatLog(BOAT_LOG_VERBOSE, "Use gasPrice from network: %s wei.", gas_price_from_net_str);
}
}
return result;
}
/******************************************************************************
@brief Set Transaction Parameter: GasLimit
Function: BoatEthTxSetGasLimit()
This function sets the gas limit of the transaction.
@return
This function returns BOAT_SUCCESS if setting is successful.\n
Otherwise it returns one of the error codes.
@param[in] tx_ptr
Pointer to the transaction structure.
@param[in] gas_limit_ptr
The gas limit is generally a fixed value on the corresponding chain.
*******************************************************************************/
BOAT_RESULT BoatEthTxSetGasLimit(BoatEthTx *tx_ptr, BoatFieldMax32B *gas_limit_ptr)
{
if( tx_ptr == NULL )
{
BoatLog(BOAT_LOG_NORMAL, "Arguments cannot be NULL.");
return BOAT_ERROR_INVALID_ARGUMENT;
}
// Set gasLimit
if( gas_limit_ptr != NULL )
{
memcpy(&tx_ptr->rawtx_fields.gaslimit,
gas_limit_ptr,
sizeof(BoatFieldMax32B));
return BOAT_SUCCESS;
}
else
{
BoatLog(BOAT_LOG_NORMAL, "Argument cannot be NULL.");
return BOAT_ERROR_INVALID_ARGUMENT;
}
}
/******************************************************************************
@brief Set Transaction Parameter: Recipient Address
Function: BoatEthTxSetRecipient()
This function sets the address of the transaction recipient.
@return
This function returns BOAT_SUCCESS if setting is successful.\n
Otherwise it returns one of the error codes.
@param[in] tx_ptr
Pointer to the transaction structure.
@param[in] address
The address of the recipient
*******************************************************************************/
BOAT_RESULT BoatEthTxSetRecipient(BoatEthTx *tx_ptr, BUINT8 address[BOAT_ETH_ADDRESS_SIZE])
{
if( tx_ptr == NULL )
{
BoatLog(BOAT_LOG_NORMAL, "Arguments cannot be NULL.");
return BOAT_ERROR_INVALID_ARGUMENT;
}
// Set recipient's address
memcpy(&tx_ptr->rawtx_fields.recipient,
address,
BOAT_ETH_ADDRESS_SIZE);
return BOAT_SUCCESS;
}
/******************************************************************************
@brief Set Transaction Parameter: Value
Function: BoatEthTxSetValue()
This function sets the value of the transaction.
@return
This function returns BOAT_SUCCESS if setting is successful.\n
Otherwise it returns one of the error codes.
@param[in] tx_ptr
Pointer to the transaction structure.
@param[in] value_ptr
The value of the transaction.\n
If <value_ptr> is NULL, it's treated as no value being transfered.
*******************************************************************************/
BOAT_RESULT BoatEthTxSetValue(BoatEthTx *tx_ptr, BoatFieldMax32B *value_ptr)
{
if( tx_ptr == NULL )
{
BoatLog(BOAT_LOG_NORMAL, "Arguments cannot be NULL.");
return BOAT_ERROR_INVALID_ARGUMENT;
}
// Set value
if( value_ptr != NULL )
{
memcpy(&tx_ptr->rawtx_fields.value,
value_ptr,
sizeof(BoatFieldMax32B));
}
else
{
// If value_ptr is NULL, value is treated as 0.
// NOTE: value.field_len == 0 has the same effect as
// value.field_len == 1 && value.field[0] == 0x00 for RLP encoding
tx_ptr->rawtx_fields.value.field_len = 0;
}
return BOAT_SUCCESS;
}
/******************************************************************************
@brief Set Transaction Parameter: Data
Function: BoatEthTxSetData()
This function sets the data of the transaction.
@return
This function returns BOAT_SUCCESS if setting is successful.\n
Otherwise it returns one of the error codes.
@param[in] tx_ptr
Pointer to the transaction structure.
@param[in] data_ptr
The data of the transaction. Note that data_ptr->field_ptr itself is only\n
a pointer without any associated storage by default. The caller must\n
allocate appropriate memory for it.\n
If <data_ptr> is NULL, it's treated as no data being transfered.
*******************************************************************************/
BOAT_RESULT BoatEthTxSetData(BoatEthTx *tx_ptr, BoatFieldVariable *data_ptr)
{
if( tx_ptr == NULL )
{
BoatLog(BOAT_LOG_NORMAL, "Arguments cannot be NULL.");
return BOAT_ERROR_INVALID_ARGUMENT;
}
// Set data
if( data_ptr != NULL )
{
// NOTE: tx_ptr->rawtx_fields.data.field_ptr is a pointer
// The caller must make sure the storage it points to is available
// until the transaction is sent.
memcpy(&tx_ptr->rawtx_fields.data,
data_ptr,
sizeof(BoatFieldVariable));
}
else
{
// If data_ptr is NULL, value is treated as 0.
// NOTE: data.field_len == 0 has the same effect as
// data.field_len == 1 && data.field_ptr[0] == 0x00 for RLP encoding
tx_ptr->rawtx_fields.data.field_len = 0;
}
return BOAT_SUCCESS;
}
/******************************************************************************
@brief Sign and send a transaction. Also call a stateful contract function.
Function: BoatEthTxSend()
This function sign and set a transaction.
BoatWalletSetXXX() and BoatTxSetXXX() functions must be properly called
before call this function.
A transaction whose recipient may be an EOA address or a contract address.
In latter case it's usually a contract function call.
This function invokes the eth_sendRawTransaction RPC method.
eth_sendRawTransaction method only applies the transaction and returns a
transaction hash. The transaction is not verified (got mined) until the
nodes in the network get into consensus about the transaction. This
function will invoke eth_getTransactionReceipt method to wait for the
transaction being mined or timeout.
If the transaction is a contract function call, the caller cannot get its
return value because the transaction is asynchronously executed. It's a
good practice to save the return value in a state variable and use
BoatEthCallContractFunc() to call a "read" contract function that could read
and return the state variable.
NOTE:
Any contract function that may change the state of the contract shall
be called in a transaction way. "state" is the "global variable" used in a
contract.
Any contract function that doesn't change the state of the contract can
be called either in a transaction way or by BoatEthCallContractFunc(), which
invokes the eth_call RPC method. However the former will consume gas and
latter doesn't consume gas.
@see BoatEthCallContractFunc()
@return
This function returns BOAT_SUCCESS if setting is successful.\n
Otherwise it returns one of the error codes.
@param[in] tx_ptr
Pointer to the transaction structure.
*******************************************************************************/
BOAT_RESULT BoatEthTxSend(BoatEthTx *tx_ptr)
{
BOAT_RESULT result;
if( tx_ptr == NULL || tx_ptr->wallet_ptr == NULL )
{
BoatLog(BOAT_LOG_NORMAL, "Arguments cannot be NULL.");
return BOAT_ERROR_INVALID_ARGUMENT;
}
if( tx_ptr->is_sync_tx == BOAT_FALSE )
{
result = EthSendRawtx(tx_ptr);
}
else
{
result = EthSendRawtxWithReceipt(tx_ptr);
}
return result;
}
/******************************************************************************
@brief Call a state-less contract function
Function: BoatEthCallContractFunc()
This function calls contract function that doesn't change the state of the
contract. "state" is the "global variable" used in a contract.
This function invokes the eth_call RPC method. eth_call method requests the
blockchain node to execute the function without affecting the block chain.
The execution runs only on the requested node thus it can return immediately
after the execution. This function synchronously return the return value
of the eth_call method, which is the return value of the contract function.
To call contract function that may change the state, use BoatEthTxSend()
instead.
If call a contract function that may change the state with
BoatEthCallContractFunc(), the function will be executed and return a value,
but none of the states will change.
@see BoatEthTxSend()
@return
This function returns the complete json message of the RPC method response.\n
If any error occurs, it returns NULL.
@param[in] tx_ptr
Transaction pointer
@param[in] func_proto_str
A string representing the prototype of the called function.\n
Note: uint is treated as uint256.\n
e.g.: for the contract function:\n
function readListByIndex(uint index) public view returns (bytes32 event_)\n
its prototype is "readListByIndex(uint256)"
@param[in] func_param_ptr
A byte stream containing the parameters to pass to the function.\n
The layout conforms to Ethereum ABI: https://solidity.readthedocs.io/en/develop/abi-spec.html\n
If <func_param_ptr> is NULL, this function doesn't take any parameter.
@param[in] func_param_len
Length of <func_param_ptr> in byte.
*******************************************************************************/
BCHAR * BoatEthCallContractFunc(
BoatEthTx *tx_ptr,
BCHAR *func_proto_str,
BUINT8 *func_param_ptr,
BUINT32 func_param_len)
{
BUINT8 function_selector[32];
// +4 for function selector, *2 for bin to HEX, + 3 for "0x" prefix and NULL terminator
BCHAR data_str[(func_param_len + 4)*2 + 3]; // Compiler MUST support C99 to allow variable-size local array
Param_eth_call param_eth_call;
BCHAR *retval_str;
if( tx_ptr == NULL || tx_ptr->wallet_ptr == NULL)
{
BoatLog(BOAT_LOG_NORMAL, "Arguments cannot be NULL.");
return NULL;
}
if( func_param_ptr == NULL && func_param_len != 0)
{
BoatLog(BOAT_LOG_NORMAL, "Arguments cannot be NULL.");
return NULL;
}
BCHAR recipient_hexstr[BOAT_ETH_ADDRESS_SIZE*2+3];
UtilityBin2Hex(
recipient_hexstr,
tx_ptr->rawtx_fields.recipient,
BOAT_ETH_ADDRESS_SIZE,
BIN2HEX_LEFTTRIM_UNFMTDATA,
BIN2HEX_PREFIX_0x_YES,
BOAT_FALSE
);
param_eth_call.to = recipient_hexstr;
// Function call consumes zero gas but gasLimit and gasPrice must be specified.
param_eth_call.gas = "0x1fffff";
param_eth_call.gasPrice = "0x8250de00";
keccak_256((BUINT8*)func_proto_str, strlen(func_proto_str), function_selector);
// Set function selector
UtilityBin2Hex(
data_str,
function_selector,
4,
BIN2HEX_LEFTTRIM_UNFMTDATA,
BIN2HEX_PREFIX_0x_YES,
BOAT_FALSE);
// Set function parameters
UtilityBin2Hex(
data_str+10, // "0x12345678" function selector prefixed
func_param_ptr,
func_param_len,
BIN2HEX_LEFTTRIM_UNFMTDATA,
BIN2HEX_PREFIX_0x_NO,
BOAT_FALSE);
param_eth_call.data = data_str;
param_eth_call.block_num_str = "latest";
retval_str = web3_eth_call( tx_ptr->wallet_ptr->web3intf_context_ptr,
tx_ptr->wallet_ptr->network_info.node_url_ptr,
¶m_eth_call);
return retval_str;
}
/******************************************************************************
@brief Transfer Ether to spceified recipient
Function: BoatEthTransfer()
This function transfer Ether from the wallet's owner account to the specified
recipient account.
Before calling this function, all necessary wallet fields such as private key,
node URL and etc. must be set correctly.
@return
This function returns BOAT_SUCCESS if transfer is successful.\n
Otherwise it returns one of the error codes.
@param[in] tx_ptr
Transaction pointer.
@param[in] value_hex_str
A string representing the value (Unit: wei) to transfer, in HEX format like\n
"0x89AB3C".\n
Note that decimal value is not accepted. If a decimal value such as "1234"\n
is specified, it's treated as "0x1234".
*******************************************************************************/
BOAT_RESULT BoatEthTransfer(BoatEthTx *tx_ptr, BCHAR * value_hex_str)
{
BoatFieldMax32B value;
BOAT_RESULT result;
if( tx_ptr == NULL || tx_ptr->wallet_ptr == NULL|| value_hex_str == NULL )
{
BoatLog(BOAT_LOG_NORMAL, "Argument cannot be NULL.");
return BOAT_ERROR_INVALID_ARGUMENT;
}
// Set nonce
result = BoatEthTxSetNonce(tx_ptr, BOAT_ETH_NONCE_AUTO);
if( result != BOAT_SUCCESS ) return BOAT_ERROR;
// Set value
value.field_len =
UtilityHex2Bin(
value.field,
32,
value_hex_str,
TRIMBIN_LEFTTRIM,
BOAT_TRUE
);
result =BoatEthTxSetValue(tx_ptr, &value);
if( result != BOAT_SUCCESS ) return BOAT_ERROR;
// Set data
result = BoatEthTxSetData(tx_ptr, NULL);
if( result != BOAT_SUCCESS ) return BOAT_ERROR;
// Perform the transaction
// NOTE: Field v,r,s are calculated automatically
result = BoatEthTxSend(tx_ptr);
if( result != BOAT_SUCCESS ) return BOAT_ERROR;
return BOAT_SUCCESS;
}
/******************************************************************************
@brief Wait for a transaction being mined.
Function: BoatEthGetTransactionReceipt()
This function polls receipt by transaction hash and waits for the transaction
being mined.
Be sure the transaction object pointed by <tx_ptr> has been called with
EthSendRawtxis().
@return
This function returns BOAT_SUCCESS if successful. Otherwise it returns one\n
of the error codes.
@param[in] tx_ptr
A pointer to the context of the transaction.
*******************************************************************************/
BOAT_RESULT BoatEthGetTransactionReceipt(BoatEthTx *tx_ptr)
{
BCHAR tx_hash_str[67];
BCHAR *tx_status_str;
Param_eth_getTransactionReceipt param_eth_getTransactionReceipt;
BSINT32 tx_mined_timeout;
BOAT_RESULT result = BOAT_SUCCESS;
if( tx_ptr == NULL || tx_ptr->wallet_ptr == NULL)
{
BoatLog(BOAT_LOG_NORMAL, "Arguments cannot be NULL.");
return BOAT_ERROR;
}
UtilityBin2Hex(
tx_hash_str,
tx_ptr->tx_hash.field,
tx_ptr->tx_hash.field_len,
BIN2HEX_LEFTTRIM_UNFMTDATA,
BIN2HEX_PREFIX_0x_YES,
BOAT_FALSE);
tx_mined_timeout = BOAT_WAIT_PENDING_TX_TIMEOUT;
param_eth_getTransactionReceipt.tx_hash_str = tx_hash_str;
do
{
BoatSleep(BOAT_MINE_INTERVAL); // Sleep waiting for the block being mined
tx_status_str = web3_eth_getTransactionReceiptStatus(tx_ptr->wallet_ptr->web3intf_context_ptr,
tx_ptr->wallet_ptr->network_info.node_url_ptr,
¶m_eth_getTransactionReceipt);
result = BoatEthPraseRpcResponseResult( tx_status_str, "status",
&tx_ptr->wallet_ptr->web3intf_context_ptr->web3_result_string_buf);
if( result != BOAT_SUCCESS )
{
BoatLog(BOAT_LOG_NORMAL, "Fail to get transaction receipt due to RPC failure.");
result = BOAT_ERROR_RPC_FAIL;
break;
}
else
{
// status of tx_status_str == "": the transaction is pending
// status of tx_status_str == "0x1": the transaction is successfully mined
// status of tx_status_str == "0x0": the transaction fails
if( tx_ptr->wallet_ptr->web3intf_context_ptr->web3_result_string_buf.field_ptr[0] != '\0' )
{
if( strcmp((BCHAR*)tx_ptr->wallet_ptr->web3intf_context_ptr->web3_result_string_buf.field_ptr, "0x1") == 0 )
{
BoatLog(BOAT_LOG_NORMAL, "Transaction has got mined.");
result = BOAT_SUCCESS;
break;
}
else
{
BoatLog(BOAT_LOG_NORMAL, "Transaction fails.");
result = BOAT_ERROR;
}
}
tx_mined_timeout -= BOAT_MINE_INTERVAL;
}
}while(tx_mined_timeout > 0);
if( tx_mined_timeout <= 0)
{
BoatLog(BOAT_LOG_NORMAL, "Wait for pending transaction timeout. This does not mean the transaction fails.");
result = BOAT_ERROR_TX_NOT_MINED;
}
return result;
}
|
gitter-badger/BoAT-X-Framework | include/boatrlp.h | /******************************************************************************
* Copyright (C) 2018-2021 aitos.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/*!@brief RLP Encoding header file
@file
boatrlp.h is the header file for RLP encoding.
*/
#ifndef __BOATRLP_H__
#define __BOATRLP_H__
#include "boatiotsdk.h"
/*!
Enum Type RlpObjectType
*/
typedef enum
{
RLP_OBJECT_TYPE_STRING = 0,
RLP_OBJECT_TYPE_LIST
}RlpObjectType;
#define RLP_STREAM_LEN_UNKNOWN (~0)
typedef struct TRlpEncodedStreamObject
{
BUINT8 *stream_ptr;
BUINT32 stream_len;
}RlpEncodedStreamObject;
typedef struct TRlpObjectTypeString
{
BUINT8 *string_ptr;
BUINT32 string_len;
}RlpObjectTypeString;
typedef struct TRlpObjectTypeList
{
struct TRlpListDescriptors *list_descriptors_ptr;
RlpEncodedStreamObject rlp_encoded_stream_object;
}RlpObjectTypeList;
typedef struct TRlpObject
{
RlpObjectType object_type;
union
{
RlpObjectTypeString object_string;
RlpObjectTypeList object_list;
};
}RlpObject;
#define MAX_RLP_LIST_DESC_NUM 15
typedef struct TRlpListDescriptors
{
BUINT32 descriptor_num;
RlpObject *rlp_object_ptr[MAX_RLP_LIST_DESC_NUM];
}RlpListDescriptors;
#ifdef __cplusplus
extern "C" {
#endif
/*!*****************************************************************************
@brief Initialize an RLP object of STRING type
Function: RlpInitStringObject()
This function initialize an RlpObject of string type. The caller allocates
the memory for struct RlpObject and the string to hold by the RlpObject. DO
NOT free the memory used by RlpObject and the string attached to the RlpObject.
The RLP encoder takes care of the memory dynamically allocated during RLP
encoding.
NOTE: Despite its name being "string", it's actually byte stream.
@see RlpInitListObject()
@return
This function returns BOAT_SUCCESS if successful.\n
Otherwise it returns one of the error codes.
@param[in] rlp_object_ptr
The pointer to a valid RlpObject.
@param[in] string_ptr
Pointer of the string to attach to <rlp_object_ptr>.\n
@param[in] string_len
Length (in byte) of <string_ptr>.
*******************************************************************************/
BOAT_RESULT RlpInitStringObject(RlpObject *rlp_object_ptr, BUINT8 *string_ptr, BUINT32 string_len);
/*!*****************************************************************************
@brief Initialize an RLP object of LIST type
Function: RlpInitListObject()
This function initialize an RlpObject of list type. The caller allocates
the memory for struct RlpObject. DO NOT free the memory used by RlpObject.
The RLP encoder takes care of the memory dynamically allocated during RLP
encoding.
NOTE: The initial RlpObject of a LIST type is empty and can later attach
other RlpObject of either STRING type or LIST type into it.
@see RlpInitStringObject()
@return
This function returns BOAT_SUCCESS if successful.\n
Otherwise it returns one of the error codes.
@param[in] rlp_object_ptr
The pointer to a valid RlpObject.
*******************************************************************************/
BOAT_RESULT RlpInitListObject(RlpObject *rlp_object_ptr);
/*!*****************************************************************************
@brief Append an RLP object to a parent RLP object of LIST type
Function: RlpEncoderAppendObjectToList()
This function appends an RlpObject (of either STRING type or LIST type) to
of a parent RlpObject of LIST type.
@return
This function returns non-negative descriptor index where the RlpObject is\n
appended if successful.\n
Otherwise it returns one of the error codes.
@param[in] to_list_object_ptr
The parent LIST RlpObject to append to.
@param[in] from_object_ptr
The child RlpObject to append.
*******************************************************************************/
BOAT_RESULT RlpEncoderAppendObjectToList(RlpObject *to_list_object_ptr, RlpObject *from_object_ptr);
/*!*****************************************************************************
@brief Replace an RLP object in a parent RLP object of LIST type
Function: RlpEncoderReplaceObjectInList()
This function replaces an RlpObject at the specified index in a parent
LIST RlpObject with another RlpObject.
NOTE: The caller takes case of the memroy used by replaced RlpObject.
@return
This function returns the replaced RlpObject's descriptor index in the parent
LIST RlpObject if successful.\n
Otherwise it returns one of the error codes.
@param[in] to_list_object_ptr
The parent LIST RlpObject to append to.
@param[in] replace_index
The descriptor index in <to_list_object_ptr> to replace.
@param[in] from_object_ptr
The RlpObject to replace with.
*******************************************************************************/
BSINT32 RlpEncoderReplaceObjectInList(RlpObject *to_list_object_ptr, BSINT32 replace_index, RlpObject *from_object_ptr);
/*!*****************************************************************************
@brief Get an RLP object pointer in a parent RLP object by its index
Function: RlpEncoderGetListDescriptor()
This function returns the RlpObject pointer at the specified index in a parent
LIST RlpObject.
NOTE: This doesn't remove the RlpObject from the parent LIST RlpObject. DO NOT
free the memroy used by the RlpObject. DO NOT modify the content of the
RlpObject.
@return
This function returns the pointer to the RlpObject specified by the descriptor\n
index in the parent if successful.\n
Otherwise it returns NULL.
@param[in] rlp_object_ptr
The parent LIST RlpObject.
@param[in] descriptor_index
The descriptor index to get the RlpObject.
*******************************************************************************/
RlpObject * RlpEncoderGetListDescriptor(RlpObject *rlp_object_ptr, BUINT32 descriptor_index);
/*!*****************************************************************************
@brief Delete an RLP object and all its children
Function: RlpRecursiveDeleteObject()
This function deletes an RlpObject and all its children RlpObject (if it's
of LIST and there should be some children).
NOTE: The caller takes care of the memory used by the struct RlpObject.
@see RlpRecursiveDeleteEncodedStream()
@return
This function doesn't return anything.
@param[in] rlp_object_ptr
The parent RlpObject to delete.
*******************************************************************************/
void RlpRecursiveDeleteObject(RlpObject *rlp_object_ptr);
/*!*****************************************************************************
@brief Delete encoded RLP stream in an RLP object and all its children
Function: RlpRecursiveDeleteEncodedStream()
This function deletes encoded RLP stream in an RlpObject and all its children
RlpObject (if it's of LIST and there should be some children).
This function only deletes the encoded RLP stream while leaves the RlpObject's
descriptor as is. Thus the tree-ed structure of its children is not affected.
This function is used in an RLP re-encoding operation. It cleans all previously
encoded RLP stream and prepares for a re-encoding.
@see RlpRecursiveDeleteObject()
@return
This function doesn't return anything.
@param[in] rlp_object_ptr
The parent RlpObject which contains the encoded RLP stream to delete.
*******************************************************************************/
void RlpRecursiveDeleteEncodedStream(RlpObject *rlp_object_ptr);
/*!*****************************************************************************
@brief Calculate the encoded RLP stream size in an RLP object and all its children
Function: RlpRecursiveCalcEncodingSize()
This function calculates the size of the encoded RLP stream in an RlpObject
and all its children RlpObject (if it's of LIST and there should be some children).
The size returned is the total size of the stream that would be encoded by
RlpEncode(). It's used to allocate memory before executing an RLP encoding
operation.
NOTE: This function doesn't actually encode the stream and doesn't allocate
any dynamic memory.
@see RlpEncode()
@return
This function returns the size of the encoded stream.
@param[in] rlp_object_ptr
The RlpObject to be encode.
@param[out] rlp_head_size_ptr
The RLP head size within the encoded stream.
*******************************************************************************/
BUINT32 RlpRecursiveCalcEncodingSize(RlpObject *rlp_object_ptr, BOAT_OUT BUINT8 *rlp_head_size_ptr);
/*!*****************************************************************************
@brief Encode an RLP stream as per RLP encoding rules.
Function: RlpEncode()
This function recursively encodes an RLP stream for the specified RlpObject
and its children (if there be).
There are 3 possible types of RLP encoding structure as per RLP rules:
1. encoded = <field>, if field_len is 1
2. encoded = <1 byte prefix>|<field>, if field_len is in range [0,55] except 1
3. encoded = <1 byte prefix>|<field_len>|<field>, if field_len >= 56
where "|" means concatenaion.
If encoding completes successfully, call RlpGetEncodedStream() to get the
encoded RLP stream.
If the RlpObject is no longer required, call RlpRecursiveDeleteObject() to
delete all tree-ed RlpObject.
@note See https://github.com/ethereum/wiki/wiki/RLP for details of the encoding rule.
@see RlpRecursiveCalcEncodingSize() RlpGetEncodedStream() RlpRecursiveDeleteObject()
@return
This function returns BOAT_SUCCESS if successful.\n
Otherwise it returns one of the error codes.
@param[in] rlp_object_ptr
The RlpObject to encode.
@param[in] parent_storage_ptr
The parent stream object to store the encoded RLP stream.\n\n
If the <rlp_object_ptr> is the most outer LIST RlpObject, <parent_storage_ptr>\n
can be specified with NULL, which allows the RLP encoder to automatically\n
calculate the stream size and allocate memory for it.\n\n
For a STRING RlpObject, the caller must calculate its size with\n
RlpRecursiveCalcEncodingSize() and allcoate <parent_storage_ptr> for it.
*******************************************************************************/
BOAT_RESULT RlpEncode(RlpObject *rlp_object_ptr, RlpEncodedStreamObject *parent_storage_ptr);
/*!*****************************************************************************
@brief Re-encode an RLP stream as per RLP encoding rules.
Function: RlpReEncode()
This function recursively cleans previously encoded RLP stream for the
specified RlpObject and re-encode the RLP stream.
@see RlpEncode()
@return
This function returns BOAT_SUCCESS if successful.\n
Otherwise it returns one of the error codes.
@param[in] rlp_object_ptr
The RlpObject to encode.
@param[in] parent_storage_ptr
The parent stream object to store the encoded RLP stream.\n\n
If the <rlp_object_ptr> is the most outer LIST RlpObject, <parent_storage_ptr>\n
can be specified with NULL, which allows the RLP encoder to automatically\n
calculate the stream size and allocate memory for it.\n\n
For a STRING RlpObject, the caller must calculate its size with\n
RlpRecursiveCalcEncodingSize() and allcoate <parent_storage_ptr> for it.
*******************************************************************************/
BOAT_RESULT RlpReEncode(RlpObject *rlp_object_ptr, RlpEncodedStreamObject *parent_storage_ptr);
/*!*****************************************************************************
@brief Get the encoded RLP stream
Function: RlpGetEncodedStream()
This function returns encoded RLP stream of the specified RlpObject.
Make sure RlpEncode() or RlpReEncode() has been successfully called for
the RlpObject.
@see RlpEncode() RlpReEncode()
@return
This function returns pointer to the encoded RLP stream object.\n
Otherwise it returns NULL.
@param[in] rlp_object_ptr
The encoded RlpObject.
*******************************************************************************/
RlpEncodedStreamObject * RlpGetEncodedStream(RlpObject *rlp_object_ptr);
#ifdef __cplusplus
}
#endif /* end of __cplusplus */
#endif
|
gitter-badger/BoAT-X-Framework | include/boattypes.h | <reponame>gitter-badger/BoAT-X-Framework<filename>include/boattypes.h
/******************************************************************************
* Copyright (C) 2018-2021 aitos.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/*!@brief Define basic types for BoAT IoT SDK.
@file
boattypes.h defines types used in BoAT IoT SDK.
*/
#ifndef __BOATTYPES_H__
#define __BOATTYPES_H__
#define BOAT_OUT
#define BOAT_IN
#define BOAT_INOUT
#define BOAT_TRUE 1
#define BOAT_FALSE 0
#define __BOATSTATIC static
#define __BOATINLINE inline
// Basic Types, prefixed with "B" to avoid possible conflict with customer's typedef
typedef bool BBOOL;
typedef char BCHAR;
typedef unsigned char BUINT8;
typedef unsigned short BUINT16;
typedef unsigned int BUINT32;
typedef unsigned long long int BUINT64;
//typedef __uint128_t BUINT128;
typedef signed char BSINT8;
typedef signed short BSINT16;
typedef signed int BSINT32;
typedef signed long long int BSINT64;
//typedef __int128_t BSINT128;
typedef BSINT32 BOAT_RESULT;
typedef BUINT8 BoatAddress[20];
//!@brief Blockchain Protocol types
typedef enum
{
BOAT_PROTOCOL_UNKNOWN = 0, //!< Placeholder for unknown protocol
BOAT_PROTOCOL_ETHEREUM, //!< Ethereum
BOAT_PROTOCOL_HLFABRIC, //!< HyperLedger Fabric
BOAT_PROTOCOL_PLATONE //!< PlatONE Enterprise consortium chain
}BoatProtocolType;
//!@brief common struct for variable length fields
typedef struct TBoatFieldVariable
{
BUINT8 *field_ptr; //!< The address of the field storage. The storage MUST be allocated before use.
BUINT32 field_len; //!< The length of the field in byte
}BoatFieldVariable;
//!@brief common struct for 4-byte (32-bit) length fields
typedef struct TBoatFieldMax4B
{
BUINT8 field[4]; //!< Field storage
BUINT32 field_len; //!< The effective length of the field in byte
}BoatFieldMax4B;
//!@brief common struct for 32-byte (256-bit) length transaction fields
typedef struct TBoatFieldMax32B
{
BUINT8 field[32]; //!< Field storage
BUINT32 field_len; //!< The effective length of the field in byte
}BoatFieldMax32B;
//!@brief common struct for 8-byte (64-bit) length transaction fields
typedef struct TBoatFieldMax8B
{
BUINT8 field[8]; //!< Field storage
BUINT32 field_len; //!< The effective length of the field in byte
}BoatFieldMax8B;
#endif
|
gitter-badger/BoAT-X-Framework | tests/case_16_platone_cov.c | /******************************************************************************
* Copyright (C) 2018-2021 aitos.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "boatiotsdk.h"
#include "boatplatone.h"
#include "my_contract.cpp.abi.h"
#include "testcommon.h"
#define TEST_PONE_PRIVATE_KEY_COV_0 "0x1234567812345678123456781234567812345678123456781234567812345678"
#define TEST_PONE_NODE_URL_COV_0 "HTTP://127.0.0.1:7545"
#define TEST_PONE_WALLET_NAME_COV_0 "./tests/platone.key"
BoatPlatoneWallet *g_case_16_platone_wallet_ptr;
BoatPlatoneWallet *wallet_ptr;
BOAT_RESULT Case_15_PlatonePreCondition_A(void)
{
BSINT32 index;
BoatPlatoneWalletConfig wallet_config;
BoatPlatoneWallet *wallet_ptr;
// Set Private Key
UtilityHex2Bin( wallet_config.priv_key_array,
32,
TEST_PONE_PRIVATE_KEY_COV_0,
TRIMBIN_TRIM_NO,
BOAT_FALSE);
wallet_config.chain_id = 1;
wallet_config.eip155_compatibility = 0;
// Set Node URL
wallet_config.node_url_str[BOAT_NODE_URL_MAX_LEN-1] = '\0';
strncpy(wallet_config.node_url_str, TEST_PONE_NODE_URL_COV_0, BOAT_NODE_URL_MAX_LEN-1);
index = BoatWalletCreate(BOAT_PROTOCOL_PLATONE, TEST_PONE_WALLET_NAME_COV_0, &wallet_config, sizeof(BoatPlatoneWalletConfig));
if( index == -1 )
{
BoatLog(BOAT_LOG_NORMAL, "Fail to create wallet.");
return BOAT_ERROR;
}
wallet_ptr = BoatGetWalletByIndex(index);
g_case_16_platone_wallet_ptr = wallet_ptr;
// Destroy private key in local variable
memset(wallet_config.priv_key_array, 0x00, 32);
return BOAT_SUCCESS;
}
BOAT_RESULT Case_boatplatoneMain(BoatPlatoneWallet *wallet_ptr)
{
BSINT32 result=BOAT_SUCCESS;
BoatDisplayCellTestResult(result, -108 == PlatoneSendRawtx( NULL ), "PlatoneSendRawtx");
BoatPlatoneTx tx_toplatone;
BoatDisplayCellTestResult(result, BOAT_SUCCESS == BoatPlatoneTxInit(wallet_ptr, &tx_toplatone, BOAT_TRUE,NULL,"0x333333","0xaac9fb1d70ee0d4b5a857a28b9c3b16114518e45",BOAT_PLATONE_TX_TYPE_CONTRACT_NULL_TERMED_STR), "BoatPlatoneTxInit");
BoatDisplayCellTestResult(result, BOAT_SUCCESS == BoatPlatoneTxSetNonce(&tx_toplatone, 0xff), "BoatPlatoneTxSetNonce");
BoatFieldMax32B value;
BoatDisplayCellTestResult(result, BOAT_SUCCESS <= (value.field_len = UtilityHex2Bin(value.field,32, "0x00",TRIMBIN_LEFTTRIM, BOAT_TRUE )), "UtilityHex2Bin");
BoatDisplayCellTestResult(result, BOAT_SUCCESS == BoatPlatoneTxSetValue(&tx_toplatone, &value), "BoatPlatoneTxSetValue");
BoatFieldVariable data;
BUINT64 tx_type_big;
// Set data (contains txtype only)
UtilityUint64ToBigend(
(BUINT8*)&tx_type_big,
0,
TRIMBIN_TRIM_NO
);
data.field_ptr = (BUINT8*)&tx_type_big;
data.field_len = sizeof(BUINT64);
BoatDisplayCellTestResult(result, BOAT_SUCCESS == BoatPlatoneTxSetData(&tx_toplatone, &data), "BoatPlatoneTxSetData");
BoatDisplayCellTestResult(result, BOAT_SUCCESS == BoatPlatoneTxSend(&tx_toplatone), "BoatPlatoneTxSend");
return BOAT_SUCCESS;
}
//api_ethereum.c
BOAT_RESULT Case_apiPlatoneMain(BoatPlatoneWallet *wallet_ptr)
{
BSINT32 result=BOAT_SUCCESS;
BoatDisplayCellTestResult(result, NULL == BoatPlatoneWalletInit(NULL, 0), "BoatPlatoneWalletInit");
BoatDisplayCellTestResult(result, -108 == BoatPlatoneWalletSetNodeUrl(NULL, "HTTP://127.0.0.1:7545"), "BoatPlatoneWalletSetNodeUrl 0");
BoatDisplayCellTestResult(result, BOAT_SUCCESS != BoatPlatoneWalletSetNodeUrl(wallet_ptr, NULL), "BoatPlatoneWalletSetNodeUrl 1");
BoatDisplayCellTestResult(result, -108 == BoatPlatoneWalletSetEIP155Comp(NULL, 1), "BoatPlatoneWalletSetEIP155Comp");
BoatDisplayCellTestResult(result, -108 == BoatPlatoneWalletSetChainId(NULL, 1), "BoatPlatoneWalletSetChainId");
BoatDisplayCellTestResult(result, NULL == BoatPlatoneWalletGetBalance(NULL, NULL), "BoatPlatoneWalletGetBalance 0");
BoatDisplayCellTestResult(result, NULL != BoatPlatoneWalletGetBalance(wallet_ptr, "0xaac9fb1d70ee0d4b5a857a28b9c3b16114518e45"), "BoatPlatoneWalletGetBalance 1");
BoatPlatoneTx tx_ptr;
BoatDisplayCellTestResult(result, BOAT_SUCCESS != BoatPlatoneTxInit(NULL,&tx_ptr,true,"0x1234","0x333333","0xaac9fb1d70ee0d4b5a857a28b9c3b16114518e45",BOAT_PLATONE_TX_TYPE_CONTRACT_NULL_TERMED_STR), "BoatPlatoneTxInit 0");
BoatDisplayCellTestResult(result, BOAT_SUCCESS == BoatPlatoneTxInit(wallet_ptr,&tx_ptr,true,"0x1234","0x333333","0xaac9fb1d70ee0d4b5a857a28b9c3b16114518e45",BOAT_PLATONE_TX_TYPE_CONTRACT_NULL_TERMED_STR), "BoatPlatoneTxInit 1");
BoatDisplayCellTestResult(result, BOAT_SUCCESS != BoatPlatoneTxSetNonce(NULL, 0x23), "BoatPlatoneTxSetNonce");
BoatDisplayCellTestResult(result, BOAT_SUCCESS != BoatPlatoneTxSetGasPrice(NULL, NULL), "BoatPlatoneTxSetGasPrice 0");
BoatDisplayCellTestResult(result, BOAT_SUCCESS == BoatPlatoneTxSetGasPrice(&tx_ptr, NULL), "BoatPlatoneTxSetGasPrice 1");
BoatDisplayCellTestResult(result, BOAT_SUCCESS != BoatPlatoneTxSetGasLimit(NULL, NULL), "BoatPlatoneTxSetGasLimit 0");
BoatDisplayCellTestResult(result, BOAT_SUCCESS != BoatPlatoneTxSetGasLimit(&tx_ptr, NULL), "BoatPlatoneTxSetGasLimit 1");
BUINT8 setrecipient[20]={0x12,0x13};
BoatDisplayCellTestResult(result, BOAT_SUCCESS != BoatPlatoneTxSetRecipient(NULL, setrecipient), "BoatPlatoneTxSetRecipient");
BoatDisplayCellTestResult(result, BOAT_SUCCESS != BoatPlatoneTxSetValue(NULL, NULL), "BoatPlatoneTxSetValue");
BoatDisplayCellTestResult(result, BOAT_SUCCESS != BoatPlatoneTxSetData(NULL, NULL), "BoatPlatoneTxSetData");
BoatDisplayCellTestResult(result, BOAT_SUCCESS != BoatPlatoneTxSend(NULL), "BoatPlatoneTxSend");
BoatDisplayCellTestResult(result, NULL == BoatPlatoneCallContractFunc( NULL,NULL, 16), "BoatPlatoneCallContractFunc 0");
tx_ptr.wallet_ptr = wallet_ptr;
BoatDisplayCellTestResult(result, NULL == BoatPlatoneCallContractFunc( &tx_ptr,NULL, 16), "BoatPlatoneCallContractFunc 1");
BoatDisplayCellTestResult(result, BOAT_ERROR == BoatPlatoneGetTransactionReceipt(NULL), "BoatPlatoneGetTransactionReceipt");
return result;
}
BOAT_RESULT Case_16_PlatONECovMain(void)
{
BOAT_RESULT case_result = BOAT_SUCCESS;
case_result += Case_15_PlatonePreCondition_A();
case_result += Case_boatplatoneMain(g_case_16_platone_wallet_ptr);
case_result += Case_apiPlatoneMain(g_case_16_platone_wallet_ptr);
BoatLog(BOAT_LOG_NORMAL, "[case_result]: %d.", case_result);
BoatWalletDelete(TEST_PONE_WALLET_NAME_COV_0);
return case_result;
}
|
gitter-badger/BoAT-X-Framework | sdk/rlp/boatrlp.c | <filename>sdk/rlp/boatrlp.c
/******************************************************************************
* Copyright (C) 2018-2020 aitos.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/*!@brief Perform RLP Encoding
@file
boatrlp.c contains functions to encode a stream as per RLP encoding rules.
*/
#include "boatinternal.h"
//!@brief Check if the descriptor capacity has empty item
#define RlpCheckListDescriptorsCapacity(rlp_list_descriptors_ptr) \
(( (rlp_list_descriptors_ptr)->descriptor_num < (MAX_RLP_LIST_DESC_NUM) ) ? BOAT_TRUE:BOAT_FALSE)
/******************************************************************************
@brief Initialize an RLP object of STRING type
Function: RlpInitStringObject()
This function initialize an RlpObject of string type. The caller allocates
the memory for struct RlpObject and the string to hold by the RlpObject. DO
NOT free the memory used by RlpObject and the string attached to the RlpObject.
The RLP encoder takes care of the memory dynamically allocated during RLP
encoding.
NOTE: Despite its name being "string", it's actually byte stream.
@see RlpInitListObject()
@return
This function returns BOAT_SUCCESS if successful.\n
Otherwise it returns one of the error codes.
@param[in] rlp_object_ptr
The pointer to a valid RlpObject.
@param[in] string_ptr
Pointer of the string to attach to <rlp_object_ptr>.\n
@param[in] string_len
Length (in byte) of <string_ptr>.
*******************************************************************************/
BOAT_RESULT RlpInitStringObject(RlpObject *rlp_object_ptr, BUINT8 *string_ptr, BUINT32 string_len)
{
if( rlp_object_ptr == NULL )
{
BoatLog(BOAT_LOG_VERBOSE, "Argument cannot be NULL.");
return BOAT_ERROR_INVALID_ARGUMENT;
}
if( string_ptr == NULL && string_len != 0 )
{
BoatLog(BOAT_LOG_VERBOSE, "NULL RLP String MUST have zero length.");
return(BOAT_ERROR_INVALID_ARGUMENT);
}
rlp_object_ptr->object_type = RLP_OBJECT_TYPE_STRING;
rlp_object_ptr->object_string.string_ptr = string_ptr;
rlp_object_ptr->object_string.string_len = string_len;
return BOAT_SUCCESS;
}
/******************************************************************************
@brief Initialize an RLP object of LIST type
Function: RlpInitListObject()
This function initialize an RlpObject of list type. The caller allocates
the memory for struct RlpObject. DO NOT free the memory used by RlpObject.
The RLP encoder takes care of the memory dynamically allocated during RLP
encoding.
NOTE: The initial RlpObject of a LIST type is empty and can later attach
other RlpObject of either STRING type or LIST type into it.
@see RlpInitStringObject()
@return
This function returns BOAT_SUCCESS if successful.\n
Otherwise it returns one of the error codes.
@param[in] rlp_object_ptr
The pointer to a valid RlpObject.
*******************************************************************************/
BOAT_RESULT RlpInitListObject(RlpObject *rlp_object_ptr)
{
RlpListDescriptors *rlp_list_descriptors_ptr;
if( rlp_object_ptr == NULL )
{
BoatLog(BOAT_LOG_VERBOSE, "Argument cannot be NULL.");
return BOAT_ERROR_INVALID_ARGUMENT;
}
rlp_object_ptr->object_type = RLP_OBJECT_TYPE_LIST;
rlp_list_descriptors_ptr = BoatMalloc(sizeof(RlpListDescriptors));
if( rlp_list_descriptors_ptr == NULL )
{
BoatLog(BOAT_LOG_VERBOSE, "Fail to allocate memory for RLP list descriptor.");
return BOAT_ERROR_OUT_OF_MEMORY;
}
rlp_list_descriptors_ptr->descriptor_num = 0;
rlp_object_ptr->object_list.list_descriptors_ptr = rlp_list_descriptors_ptr;
rlp_object_ptr->object_list.rlp_encoded_stream_object.stream_ptr = NULL;
rlp_object_ptr->object_list.rlp_encoded_stream_object.stream_len = 0;
return BOAT_SUCCESS;
}
/******************************************************************************
@brief Append an RLP object to a parent RLP object of LIST type
Function: RlpEncoderAppendObjectToList()
This function appends an RlpObject (of either STRING type or LIST type) to
of a parent RlpObject of LIST type.
@return
This function returns non-negative descriptor index where the RlpObject is\n
appended if successful.\n
Otherwise it returns one of the error codes.
@param[in] to_list_object_ptr
The parent LIST RlpObject to append to.
@param[in] from_object_ptr
The child RlpObject to append.
*******************************************************************************/
BSINT32 RlpEncoderAppendObjectToList(RlpObject *to_list_object_ptr, RlpObject *from_object_ptr)
{
RlpListDescriptors *to_rlp_list_descriptors_ptr;
BUINT32 descriptor_index;
boat_try_declare;
if( to_list_object_ptr == NULL || from_object_ptr == NULL )
{
BoatLog(BOAT_LOG_VERBOSE, "Argument cannot be NULL.");
boat_throw(BOAT_ERROR_INVALID_ARGUMENT, RlpEncoderAppendObjectToList_cleanup);
}
if( to_list_object_ptr->object_type != RLP_OBJECT_TYPE_LIST )
{
BoatLog(BOAT_LOG_VERBOSE, "\"To RLP Object\" MUST be type List.");
boat_throw(BOAT_ERROR_INVALID_ARGUMENT, RlpEncoderAppendObjectToList_cleanup);
}
if( to_list_object_ptr->object_list.list_descriptors_ptr == NULL )
{
BoatLog(BOAT_LOG_VERBOSE, "List descriptors of \"To RLP Object\" MUST be available.");
boat_throw(BOAT_ERROR_INVALID_ARGUMENT, RlpEncoderAppendObjectToList_cleanup);
}
to_rlp_list_descriptors_ptr = to_list_object_ptr->object_list.list_descriptors_ptr;
if( RlpCheckListDescriptorsCapacity(to_rlp_list_descriptors_ptr) != BOAT_TRUE )
{
BoatLog(BOAT_LOG_VERBOSE, "\"To RLP Object\"\'s RLP descriptors are full.");
boat_throw(BOAT_ERROR_RLP_ENCODING_FAIL, RlpEncoderAppendObjectToList_cleanup);
}
if( from_object_ptr->object_type == RLP_OBJECT_TYPE_STRING )
{
if( from_object_ptr->object_string.string_ptr == NULL
&& from_object_ptr->object_string.string_len != 0 )
{
BoatLog(BOAT_LOG_VERBOSE, "\"From RLP Object\" is NULL String with non-zero length.");
boat_throw(BOAT_ERROR_INVALID_ARGUMENT, RlpEncoderAppendObjectToList_cleanup);
}
}
else if( from_object_ptr->object_type == RLP_OBJECT_TYPE_LIST )
{
if( from_object_ptr->object_list.list_descriptors_ptr == NULL )
{
BoatLog(BOAT_LOG_VERBOSE, "\"From RLP List Object\" MUST have list descriptors filled.");
boat_throw(BOAT_ERROR_INVALID_ARGUMENT, RlpEncoderAppendObjectToList_cleanup);
}
}
else
{
BoatLog(BOAT_LOG_VERBOSE, "Unknown \"From RLP Object\" type: %d.", from_object_ptr->object_type);
boat_throw(BOAT_ERROR_RLP_ENCODING_FAIL, RlpEncoderAppendObjectToList_cleanup);
}
descriptor_index = to_rlp_list_descriptors_ptr->descriptor_num;
to_rlp_list_descriptors_ptr->rlp_object_ptr[descriptor_index] = from_object_ptr;
to_rlp_list_descriptors_ptr->descriptor_num++;
boat_catch(RlpEncoderAppendObjectToList_cleanup)
{
BoatLog(BOAT_LOG_VERBOSE, "Exception: %d", boat_exception);
return boat_exception;
}
return (descriptor_index);
}
/******************************************************************************
@brief Replace an RLP object in a parent RLP object of LIST type
Function: RlpEncoderReplaceObjectInList()
This function replaces an RlpObject at the specified index in a parent
LIST RlpObject with another RlpObject.
NOTE: The caller takes case of the memroy used by replaced RlpObject.
@return
This function returns the replaced RlpObject's descriptor index in the parent
LIST RlpObject if successful.\n
Otherwise it returns one of the error codes.
@param[in] to_list_object_ptr
The parent LIST RlpObject to append to.
@param[in] replace_index
The descriptor index in <to_list_object_ptr> to replace.
@param[in] from_object_ptr
The RlpObject to replace with.
*******************************************************************************/
BSINT32 RlpEncoderReplaceObjectInList(RlpObject *to_list_object_ptr, BSINT32 replace_index, RlpObject *from_object_ptr)
{
boat_try_declare;
if( to_list_object_ptr == NULL || replace_index < 0 || from_object_ptr == NULL )
{
BoatLog(BOAT_LOG_VERBOSE, "Argument cannot be NULL.");
boat_throw(BOAT_ERROR_INVALID_ARGUMENT, RlpEncoderReplaceObjectInList_cleanup);
}
if( to_list_object_ptr->object_type != RLP_OBJECT_TYPE_LIST )
{
BoatLog(BOAT_LOG_VERBOSE, "\"To RLP Object\" MUST be type List.");
boat_throw(BOAT_ERROR_INVALID_ARGUMENT, RlpEncoderReplaceObjectInList_cleanup);
}
if( to_list_object_ptr->object_list.list_descriptors_ptr == NULL )
{
BoatLog(BOAT_LOG_VERBOSE, "List descriptors of \"To RLP Object\" MUST be available.");
boat_throw(BOAT_ERROR_INVALID_ARGUMENT, RlpEncoderReplaceObjectInList_cleanup);
}
if( replace_index >= to_list_object_ptr->object_list.list_descriptors_ptr->descriptor_num )
{
BoatLog(BOAT_LOG_VERBOSE, "replace_index (%d) MUST be less than descriptor_num (%u).", replace_index, to_list_object_ptr->object_list.list_descriptors_ptr->descriptor_num);
boat_throw(BOAT_ERROR_RLP_ENCODING_FAIL, RlpEncoderReplaceObjectInList_cleanup);
}
if( from_object_ptr->object_type == RLP_OBJECT_TYPE_STRING )
{
if( from_object_ptr->object_string.string_ptr == NULL
&& from_object_ptr->object_string.string_len != 0 )
{
BoatLog(BOAT_LOG_VERBOSE, "\"From RLP Object\" is NULL String with non-zero length.");
boat_throw(BOAT_ERROR_INVALID_ARGUMENT, RlpEncoderReplaceObjectInList_cleanup);
}
}
else if( from_object_ptr->object_type == RLP_OBJECT_TYPE_LIST )
{
if( from_object_ptr->object_list.list_descriptors_ptr == NULL )
{
BoatLog(BOAT_LOG_VERBOSE, "\"From RLP List Object\" MUST have list descriptors filled.");
boat_throw(BOAT_ERROR_INVALID_ARGUMENT, RlpEncoderReplaceObjectInList_cleanup);
}
}
else
{
BoatLog(BOAT_LOG_VERBOSE, "Unknown \"From RLP Object\" type: %d.", from_object_ptr->object_type);
boat_throw(BOAT_ERROR_RLP_ENCODING_FAIL, RlpEncoderReplaceObjectInList_cleanup);
}
to_list_object_ptr->object_list.list_descriptors_ptr->rlp_object_ptr[replace_index] = from_object_ptr;
boat_catch(RlpEncoderReplaceObjectInList_cleanup)
{
BoatLog(BOAT_LOG_VERBOSE, "Exception: %d", boat_exception);
return boat_exception;
}
return replace_index;
}
/******************************************************************************
@brief Get an RLP object pointer in a parent RLP object by its index
Function: RlpEncoderGetListDescriptor()
This function returns the RlpObject pointer at the specified index in a parent
LIST RlpObject.
NOTE: This doesn't remove the RlpObject from the parent LIST RlpObject. DO NOT
free the memroy used by the RlpObject. DO NOT modify the content of the
RlpObject.
@return
This function returns the pointer to the RlpObject specified by the descriptor\n
index in the parent if successful.\n
Otherwise it returns NULL.
@param[in] rlp_object_ptr
The parent LIST RlpObject.
@param[in] descriptor_index
The descriptor index to get the RlpObject.
*******************************************************************************/
RlpObject * RlpEncoderGetListDescriptor(RlpObject *rlp_object_ptr, BUINT32 descriptor_index)
{
RlpListDescriptors *rlp_list_descriptors_ptr;
if( rlp_object_ptr == NULL)
{
BoatLog(BOAT_LOG_VERBOSE, "Argument cannot be NULL.");
return NULL;
}
if( rlp_object_ptr->object_type != RLP_OBJECT_TYPE_LIST )
{
BoatLog(BOAT_LOG_VERBOSE, "RLP Object MUST be type List.");
return NULL;
}
if( rlp_object_ptr->object_list.list_descriptors_ptr == NULL )
{
BoatLog(BOAT_LOG_VERBOSE, "List descriptors of RLP Object MUST be available.");
return NULL;
}
rlp_list_descriptors_ptr = rlp_object_ptr->object_list.list_descriptors_ptr;
if( descriptor_index >= rlp_list_descriptors_ptr->descriptor_num )
{
if( rlp_list_descriptors_ptr->descriptor_num == 0 )
{
BoatLog(BOAT_LOG_VERBOSE, "Descriptor list of the RLP object is empty.");
}
else
{
BoatLog(BOAT_LOG_VERBOSE, "Descriptor index %u is out of range: [0, %u].", descriptor_index, rlp_list_descriptors_ptr->descriptor_num - 1);
}
return NULL;
}
return rlp_list_descriptors_ptr->rlp_object_ptr[descriptor_index];
}
/******************************************************************************
@brief Delete an RLP object and all its children
Function: RlpRecursiveDeleteObject()
This function deletes an RlpObject and all its children RlpObject (if it's
of LIST and there should be some children).
NOTE: The caller takes care of the memory used by the struct RlpObject.
@see RlpRecursiveDeleteEncodedStream()
@return
This function doesn't return anything.
@param[in] rlp_object_ptr
The parent RlpObject to delete.
*******************************************************************************/
void RlpRecursiveDeleteObject(RlpObject *rlp_object_ptr)
{
RlpListDescriptors *rlp_list_descriptors_ptr;
BUINT32 descriptor_index;
if( rlp_object_ptr == NULL )
{
return;
}
if( rlp_object_ptr->object_type != RLP_OBJECT_TYPE_LIST )
{
return;
}
if( rlp_object_ptr->object_list.rlp_encoded_stream_object.stream_ptr != NULL )
{
BoatFree(rlp_object_ptr->object_list.rlp_encoded_stream_object.stream_ptr);
rlp_object_ptr->object_list.rlp_encoded_stream_object.stream_ptr = NULL;
rlp_object_ptr->object_list.rlp_encoded_stream_object.stream_len = 0;
}
rlp_list_descriptors_ptr = rlp_object_ptr->object_list.list_descriptors_ptr;
if( rlp_list_descriptors_ptr == NULL )
{
return;
}
for( descriptor_index = 0;
descriptor_index < rlp_list_descriptors_ptr->descriptor_num;
descriptor_index++ )
{
RlpRecursiveDeleteObject(rlp_list_descriptors_ptr->rlp_object_ptr[descriptor_index]);
}
BoatFree(rlp_list_descriptors_ptr);
rlp_object_ptr->object_list.list_descriptors_ptr = NULL;
return;
}
/******************************************************************************
@brief Delete encoded RLP stream in an RLP object and all its children
Function: RlpRecursiveDeleteEncodedStream()
This function deletes encoded RLP stream in an RlpObject and all its children
RlpObject (if it's of LIST and there should be some children).
This function only deletes the encoded RLP stream while leaves the RlpObject's
descriptor as is. Thus the tree-ed structure of its children is not affected.
This function is used in an RLP re-encoding operation. It cleans all previously
encoded RLP stream and prepares for a re-encoding.
@see RlpRecursiveDeleteObject()
@return
This function doesn't return anything.
@param[in] rlp_object_ptr
The parent RlpObject which contains the encoded RLP stream to delete.
*******************************************************************************/
void RlpRecursiveDeleteEncodedStream(RlpObject *rlp_object_ptr)
{
RlpListDescriptors *rlp_list_descriptors_ptr;
BUINT32 descriptor_index;
if( rlp_object_ptr == NULL )
{
return;
}
if( rlp_object_ptr->object_type != RLP_OBJECT_TYPE_LIST )
{
return;
}
if( rlp_object_ptr->object_list.rlp_encoded_stream_object.stream_ptr != NULL )
{
BoatFree(rlp_object_ptr->object_list.rlp_encoded_stream_object.stream_ptr);
rlp_object_ptr->object_list.rlp_encoded_stream_object.stream_ptr = NULL;
rlp_object_ptr->object_list.rlp_encoded_stream_object.stream_len = 0;
}
rlp_list_descriptors_ptr = rlp_object_ptr->object_list.list_descriptors_ptr;
if( rlp_list_descriptors_ptr == NULL )
{
return;
}
for( descriptor_index = 0;
descriptor_index < rlp_list_descriptors_ptr->descriptor_num;
descriptor_index++ )
{
RlpRecursiveDeleteEncodedStream(rlp_list_descriptors_ptr->rlp_object_ptr[descriptor_index]);
}
return;
}
/******************************************************************************
@brief Calculate the encoded RLP stream size in an RLP object and all its children
Function: RlpRecursiveCalcEncodingSize()
This function calculates the size of the encoded RLP stream in an RlpObject
and all its children RlpObject (if it's of LIST and there should be some children).
The size returned is the total size of the stream that would be encoded by
RlpEncode(). It's used to allocate memory before executing an RLP encoding
operation.
NOTE: This function doesn't actually encode the stream and doesn't allocate
any dynamic memory.
@see RlpEncode()
@return
This function returns the size of the encoded stream.
@param[in] rlp_object_ptr
The RlpObject to be encode.
@param[out] rlp_head_size_ptr
The RLP head size within the encoded stream.
*******************************************************************************/
BUINT32 RlpRecursiveCalcEncodingSize(RlpObject *rlp_object_ptr, BOAT_OUT BUINT8 *rlp_head_size_ptr)
{
BUINT32 encoded_stream_len;
BUINT32 sub_field_encoded_stream_len;
BUINT32 sum_of_sub_field_len;
BUINT8 trimmed_field_len[8];
BUINT8 trimmed_sizeof_field_len;
BUINT8 *field_ptr;
BUINT32 field_len;
RlpListDescriptors *rlp_list_descriptors_ptr;
BUINT32 descriptor_index;
if( rlp_object_ptr == NULL )
{
BoatLog(BOAT_LOG_VERBOSE, "Argument cannot be NULL.");
return RLP_STREAM_LEN_UNKNOWN;
}
if( rlp_object_ptr->object_type == RLP_OBJECT_TYPE_STRING )
{
field_ptr = rlp_object_ptr->object_string.string_ptr;
field_len = rlp_object_ptr->object_string.string_len;
if( field_ptr == NULL && field_len != 0 )
{
BoatLog(BOAT_LOG_VERBOSE, "String cannot be null unless its length is 0.");
return RLP_STREAM_LEN_UNKNOWN;
}
// Case 1. encoded stream = <field>, if field_len is 1
if( field_len == 1 && field_ptr[0] <= 0x7f)
{
if( rlp_head_size_ptr != NULL ) *rlp_head_size_ptr = 0;
encoded_stream_len = 1;
}
else
{
// Case 2. encoded stream = <1 byte prefix>|<field>, if field_len is in range [0,55] except 1
if( field_len <= 55 )
{
if( rlp_head_size_ptr != NULL ) *rlp_head_size_ptr = 1;
encoded_stream_len = 1 + field_len;
}
else
{
// Case 3. encoded stream = <1 byte prefix>|<field_len>|<field>, if field_len >= 56
// Calculate trimmed size of <field_len>
trimmed_sizeof_field_len = UtilityUint32ToBigend(
trimmed_field_len,
field_len,
TRIMBIN_LEFTTRIM
);
if( rlp_head_size_ptr != NULL ) *rlp_head_size_ptr = 1 + trimmed_sizeof_field_len;
encoded_stream_len = 1 + trimmed_sizeof_field_len + field_len;
}
}
}
else if( rlp_object_ptr->object_type == RLP_OBJECT_TYPE_LIST )
{
sum_of_sub_field_len = 0;
rlp_list_descriptors_ptr = rlp_object_ptr->object_list.list_descriptors_ptr;
if( rlp_list_descriptors_ptr == NULL )
{
return RLP_STREAM_LEN_UNKNOWN;
}
for( descriptor_index = 0;
descriptor_index < rlp_list_descriptors_ptr->descriptor_num;
descriptor_index++ )
{
sub_field_encoded_stream_len = RlpRecursiveCalcEncodingSize( rlp_list_descriptors_ptr->rlp_object_ptr[descriptor_index], NULL);
if( sub_field_encoded_stream_len != RLP_STREAM_LEN_UNKNOWN )
{
sum_of_sub_field_len += sub_field_encoded_stream_len;
}
else
{
sum_of_sub_field_len = RLP_STREAM_LEN_UNKNOWN;
break;
}
}
if( sum_of_sub_field_len == RLP_STREAM_LEN_UNKNOWN )
{
encoded_stream_len = RLP_STREAM_LEN_UNKNOWN;
}
else
{
// Case 4.(LIST) encoded stream = <1 byte prefix>|<field>, if field_len is in range [0,55]
if( sum_of_sub_field_len <= 55 )
{
if( rlp_head_size_ptr != NULL ) *rlp_head_size_ptr = 1;
encoded_stream_len = 1 + sum_of_sub_field_len;
}
else
{
// Case 5.(LIST) encoded stream = <1 byte prefix>|<field_len>|<field>, if field_len >= 56
// Calculate trimmed size of <field_len>
trimmed_sizeof_field_len = UtilityUint32ToBigend(
trimmed_field_len,
sum_of_sub_field_len,
TRIMBIN_LEFTTRIM
);
if( rlp_head_size_ptr != NULL ) *rlp_head_size_ptr = 1 + trimmed_sizeof_field_len;
encoded_stream_len = 1 + trimmed_sizeof_field_len + sum_of_sub_field_len;
}
}
}
else
{
*rlp_head_size_ptr = 0;
encoded_stream_len = RLP_STREAM_LEN_UNKNOWN;
BoatLog(BOAT_LOG_VERBOSE, "Unknown RLP Object type: %d.", rlp_object_ptr->object_type);
}
return encoded_stream_len;
}
/******************************************************************************
@brief Encode an RLP stream as per RLP encoding rules.
Function: RlpEncode()
This function recursively encodes an RLP stream for the specified RlpObject
and its children (if there be).
There are 3 possible types of RLP encoding structure as per RLP rules:
1. encoded = <field>, if field_len is 1
2. encoded = <1 byte prefix>|<field>, if field_len is in range [0,55] except 1
3. encoded = <1 byte prefix>|<field_len>|<field>, if field_len >= 56
where "|" means concatenaion.
If encoding completes successfully, call RlpGetEncodedStream() to get the
encoded RLP stream.
If the RlpObject is no longer required, call RlpRecursiveDeleteObject() to
delete all tree-ed RlpObject.
@note See https://github.com/ethereum/wiki/wiki/RLP for details of the encoding rule.
@see RlpRecursiveCalcEncodingSize() RlpGetEncodedStream() RlpRecursiveDeleteObject()
@return
This function returns BOAT_SUCCESS if successful.\n
Otherwise it returns one of the error codes.
@param[in] rlp_object_ptr
The RlpObject to encode.
@param[in] parent_storage_ptr
The parent stream object to store the encoded RLP stream.\n\n
If the <rlp_object_ptr> is the most outer LIST RlpObject, <parent_storage_ptr>\n
can be specified with NULL, which allows the RLP encoder to automatically\n
calculate the stream size and allocate memory for it.\n\n
For a STRING RlpObject, the caller must calculate its size with\n
RlpRecursiveCalcEncodingSize() and allcoate <parent_storage_ptr> for it.
*******************************************************************************/
BOAT_RESULT RlpEncode(RlpObject *rlp_object_ptr, RlpEncodedStreamObject *parent_storage_ptr)
{
RlpEncodedStreamObject stream_object;
RlpListDescriptors *rlp_list_descriptors_ptr;
BUINT32 descriptor_index;
BUINT32 rlp_encoded_stream_len;
BUINT8 rlp_head_size;
BUINT32 sub_field_rlp_stream_len;
BUINT32 field_len;
const BUINT8 *field_ptr;
BUINT32 offset;
BUINT8 trimmed_field_len[8];
BUINT8 trimmed_sizeof_field_len;
BOAT_RESULT result;
#define RLP_PREFIX_BASE_STRING 0x80
#define RLP_PREFIX_BASE_LIST 0xC0
boat_try_declare;
if( rlp_object_ptr == NULL )
{
BoatLog(BOAT_LOG_VERBOSE, "Argument cannot be NULL.");
boat_throw(BOAT_ERROR_INVALID_ARGUMENT, RlpEncode_cleanup);
}
rlp_encoded_stream_len = RlpRecursiveCalcEncodingSize(rlp_object_ptr, &rlp_head_size);
if( rlp_encoded_stream_len == RLP_STREAM_LEN_UNKNOWN )
{
BoatLog(BOAT_LOG_VERBOSE, "Fail to calculate RLP stream size.");
boat_throw(BOAT_ERROR_RLP_ENCODING_FAIL, RlpEncode_cleanup);
}
if( parent_storage_ptr != NULL )
{
if( parent_storage_ptr->stream_ptr == NULL
|| parent_storage_ptr->stream_len < rlp_encoded_stream_len )
{
BoatLog(BOAT_LOG_VERBOSE, "Parent storage doesn't have enough space to hold encoded String.");
boat_throw(BOAT_ERROR_RLP_ENCODING_FAIL, RlpEncode_cleanup);
}
}
if( rlp_object_ptr->object_type == RLP_OBJECT_TYPE_STRING )
{
if( parent_storage_ptr == NULL )
{
BoatLog(BOAT_LOG_VERBOSE, "<parent_storage_ptr> cannot be NULL if RLP object is type String.");
boat_throw(BOAT_ERROR_INVALID_ARGUMENT, RlpEncode_cleanup);
}
if( rlp_object_ptr->object_string.string_ptr == NULL
&& rlp_object_ptr->object_string.string_len != 0 )
{
BoatLog(BOAT_LOG_VERBOSE, "\"From RLP Object\" is NULL String with non-zero length.");
boat_throw(BOAT_ERROR_INVALID_ARGUMENT, RlpEncode_cleanup);
}
// Ready to encode a String Object
field_len = rlp_object_ptr->object_string.string_len;
field_ptr = rlp_object_ptr->object_string.string_ptr;
offset = 0;
// Case 1. encoded stream = <field>, if field_len is 1
if( field_len == 1 && field_ptr[0] <= 0x7f)
{
// <field> only
parent_storage_ptr->stream_ptr[offset++] = field_ptr[0];
}
else
{
// Case 2. encoded stream = <1 byte prefix>|<field>, if field_len is in range [0,55] except 1
if( field_len <= 55 )
{
// <prefix>
parent_storage_ptr->stream_ptr[offset++] = RLP_PREFIX_BASE_STRING + field_len;
// <field>
if( field_len != 0 )
{
memcpy(parent_storage_ptr->stream_ptr + offset, field_ptr, field_len);
offset += field_len;
}
}
else
{
// Case 3. encoded stream = <1 byte prefix>|<field_len>|<field>, if field_len >= 56
// Calculate trimmed size of <field_len>
trimmed_sizeof_field_len = UtilityUint32ToBigend(
trimmed_field_len,
field_len,
TRIMBIN_LEFTTRIM
);
// <prefix>
parent_storage_ptr->stream_ptr[offset++] = RLP_PREFIX_BASE_STRING + trimmed_sizeof_field_len + 55;
// <field_len>
memcpy(parent_storage_ptr->stream_ptr + offset, trimmed_field_len, trimmed_sizeof_field_len);
offset += trimmed_sizeof_field_len;
// <field>
memcpy(parent_storage_ptr->stream_ptr + offset, field_ptr, field_len);
offset += field_len;
if( offset != rlp_encoded_stream_len )
{
BoatLog(BOAT_LOG_CRITICAL, "RLP encoding internal error: Error Size, memory overflowing.");
boat_throw(BOAT_ERROR_RLP_ENCODING_FAIL, RlpEncode_cleanup);
}
}
}
}
else if( rlp_object_ptr->object_type == RLP_OBJECT_TYPE_LIST )
{
rlp_object_ptr->object_list.rlp_encoded_stream_object.stream_ptr =
BoatMalloc(rlp_encoded_stream_len);
if( rlp_object_ptr->object_list.rlp_encoded_stream_object.stream_ptr == NULL )
{
BoatLog(BOAT_LOG_VERBOSE, "Fail to allocate memory for RLP encoded stream.");
boat_throw(BOAT_ERROR_OUT_OF_MEMORY, RlpEncode_cleanup);
}
rlp_object_ptr->object_list.rlp_encoded_stream_object.stream_len = rlp_encoded_stream_len;
stream_object.stream_ptr = rlp_object_ptr->object_list.rlp_encoded_stream_object.stream_ptr + rlp_head_size;
stream_object.stream_len = rlp_object_ptr->object_list.rlp_encoded_stream_object.stream_len - rlp_head_size;
rlp_list_descriptors_ptr = rlp_object_ptr->object_list.list_descriptors_ptr;
if( rlp_list_descriptors_ptr == NULL )
{
BoatLog(BOAT_LOG_VERBOSE, "RLP List descriptor is NULL.");
boat_throw(BOAT_ERROR_RLP_ENCODING_FAIL, RlpEncode_cleanup);
}
for( descriptor_index = 0;
descriptor_index < rlp_list_descriptors_ptr->descriptor_num;
descriptor_index++ )
{
sub_field_rlp_stream_len = RlpRecursiveCalcEncodingSize(rlp_list_descriptors_ptr->rlp_object_ptr[descriptor_index], NULL);
if( sub_field_rlp_stream_len == RLP_STREAM_LEN_UNKNOWN )
{
BoatLog(BOAT_LOG_VERBOSE, "Fail to calculate RLP stream size.");
boat_throw(BOAT_ERROR_RLP_ENCODING_FAIL, RlpEncode_cleanup);
}
result = RlpEncode(rlp_list_descriptors_ptr->rlp_object_ptr[descriptor_index], &stream_object);
if( result != BOAT_SUCCESS )
{
BoatLog(BOAT_LOG_NORMAL, "RLP encoding fails.");
boat_throw(BOAT_ERROR_RLP_ENCODING_FAIL, RlpEncode_cleanup);
}
if( stream_object.stream_len < sub_field_rlp_stream_len )
{
BoatLog(BOAT_LOG_CRITICAL, "RLP encoding internal error: Error Size.");
boat_throw(BOAT_ERROR_RLP_ENCODING_FAIL, RlpEncode_cleanup);
}
stream_object.stream_ptr += sub_field_rlp_stream_len;
stream_object.stream_len -= sub_field_rlp_stream_len;
}
// Fill RLP List Head
offset = 0;
// Case 4.(LIST) encoded stream = <1 byte prefix>|<field>, if field_len is in range [0,55]
if( (rlp_encoded_stream_len - rlp_head_size) <= 55 )
{
// <prefix>
rlp_object_ptr->object_list.rlp_encoded_stream_object.stream_ptr[offset++] = RLP_PREFIX_BASE_LIST + (rlp_encoded_stream_len - rlp_head_size);
}
else
{
// Case 5.(LIST) encoded stream = <1 byte prefix>|<field_len>|<field>, if field_len >= 56
// Calculate trimmed size of <field_len>
trimmed_sizeof_field_len = UtilityUint32ToBigend(
trimmed_field_len,
(rlp_encoded_stream_len - rlp_head_size),
TRIMBIN_LEFTTRIM
);
// <prefix>
rlp_object_ptr->object_list.rlp_encoded_stream_object.stream_ptr[offset++] = RLP_PREFIX_BASE_LIST + trimmed_sizeof_field_len + 55;
// <field_len>
memcpy( rlp_object_ptr->object_list.rlp_encoded_stream_object.stream_ptr + offset,
trimmed_field_len,
trimmed_sizeof_field_len);
offset += trimmed_sizeof_field_len;
}
if( parent_storage_ptr != NULL )
{
memcpy( parent_storage_ptr->stream_ptr,
rlp_object_ptr->object_list.rlp_encoded_stream_object.stream_ptr,
rlp_encoded_stream_len);
}
}
else
{
BoatLog(BOAT_LOG_VERBOSE, "Unknown RLP Object type: %d.", rlp_object_ptr->object_type);
boat_throw(BOAT_ERROR_RLP_ENCODING_FAIL, RlpEncode_cleanup);
}
boat_catch(RlpEncode_cleanup)
{
BoatLog(BOAT_LOG_VERBOSE, "Exception: %d", boat_exception);
result = boat_exception;
}
else
{
result = BOAT_SUCCESS;
}
if( parent_storage_ptr != NULL )
{
if( rlp_object_ptr->object_type == RLP_OBJECT_TYPE_LIST )
{
if( rlp_object_ptr->object_list.rlp_encoded_stream_object.stream_ptr != NULL )
{
BoatFree(rlp_object_ptr->object_list.rlp_encoded_stream_object.stream_ptr);
rlp_object_ptr->object_list.rlp_encoded_stream_object.stream_ptr = NULL;
rlp_object_ptr->object_list.rlp_encoded_stream_object.stream_len = 0;
}
}
}
return result;
}
/******************************************************************************
@brief Re-encode an RLP stream as per RLP encoding rules.
Function: RlpReEncode()
This function recursively cleans previously encoded RLP stream for the
specified RlpObject and re-encode the RLP stream.
@see RlpEncode()
@return
This function returns BOAT_SUCCESS if successful.\n
Otherwise it returns one of the error codes.
@param[in] rlp_object_ptr
The RlpObject to encode.
@param[in] parent_storage_ptr
The parent stream object to store the encoded RLP stream.\n\n
If the <rlp_object_ptr> is the most outer LIST RlpObject, <parent_storage_ptr>\n
can be specified with NULL, which allows the RLP encoder to automatically\n
calculate the stream size and allocate memory for it.\n\n
For a STRING RlpObject, the caller must calculate its size with\n
RlpRecursiveCalcEncodingSize() and allcoate <parent_storage_ptr> for it.
*******************************************************************************/
BOAT_RESULT RlpReEncode(RlpObject *rlp_object_ptr, RlpEncodedStreamObject *parent_storage_ptr)
{
if( rlp_object_ptr == NULL )
{
BoatLog(BOAT_LOG_VERBOSE, "Argument cannot be NULL.");
return BOAT_ERROR_INVALID_ARGUMENT;
}
RlpRecursiveDeleteEncodedStream(rlp_object_ptr);
return(RlpEncode(rlp_object_ptr, parent_storage_ptr));
}
/******************************************************************************
@brief Get the encoded RLP stream
Function: RlpGetEncodedStream()
This function returns encoded RLP stream of the specified RlpObject.
Make sure RlpEncode() or RlpReEncode() has been successfully called for
the RlpObject.
@see RlpEncode() RlpReEncode()
@return
This function returns pointer to the encoded RLP stream object.\n
Otherwise it returns NULL.
@param[in] rlp_object_ptr
The encoded RlpObject.
*******************************************************************************/
RlpEncodedStreamObject * RlpGetEncodedStream(RlpObject *rlp_object_ptr)
{
if( rlp_object_ptr == NULL )
{
BoatLog(BOAT_LOG_VERBOSE, "Argument cannot be NULL.");
return NULL;
}
if( rlp_object_ptr->object_type == RLP_OBJECT_TYPE_LIST )
{
return &(rlp_object_ptr->object_list.rlp_encoded_stream_object);
}
return NULL;
}
|
gitter-badger/BoAT-X-Framework | sdk/wallet/boatwallet.c | <gh_stars>1-10
/******************************************************************************
* Copyright (C) 2018-2021 aitos.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/*!@brief Boatwallet SDK entry
@file
boatwallet.c is the SDK main entry.
@author aitos.io
*/
#include "boatinternal.h"
#include "boatwallet.h"
#include "web3intf.h"
#include "boatprotocols.h"
#include "rpcintf.h"
#include "randgenerator.h"
#include "bignum.h"
#include "cJSON.h"
#include "persiststore.h"
BoatIotSdkContext g_boat_iot_sdk_context;
/******************************************************************************
@brief Initialize Boat IoT SDK
Function: BoatIotSdkInit()
This function initialize global context of Boat IoT SDK.
BoatIotSdkInit() MUST be called before any use of BoAT IoT SDK per process.
BoatIotSdkDeInit() MUST be called after use of BoAT IoT SDK.
@see BoatIotSdkDeInit()
@return
This function returns BOAT_SUCCESS if initialization is successful.\n
Otherwise it returns BOAT_ERROR.
@param This function doesn't take any argument.
*******************************************************************************/
BOAT_RESULT BoatIotSdkInit(void)
{
BUINT32 i;
cJSON_Hooks hooks;
#if RPC_USE_LIBCURL == 1
CURLcode curl_result;
#endif
hooks.malloc_fn = BoatMalloc;
hooks.free_fn = BoatFree;
cJSON_InitHooks(&hooks);
// For Multi-Thread Support: CreateMutex Here
for( i = 0; i < BOAT_MAX_WALLET_NUM; i++ )
{
g_boat_iot_sdk_context.wallet_list[i].is_used = BOAT_FALSE;
g_boat_iot_sdk_context.wallet_list[i].wallet_ptr = NULL;
}
#if RPC_USE_LIBCURL == 1
curl_result = curl_global_init(CURL_GLOBAL_DEFAULT);
if( curl_result != CURLE_OK)
{
BoatLog(BOAT_LOG_CRITICAL, "Unable to initialize curl.");
return BOAT_ERROR;
}
#endif
return BOAT_SUCCESS;
}
/******************************************************************************
@brief De-initialize BoAT IoT SDK
Function: BoatIotSdkDeInit()
This function de-initialize context of BoAT IoT SDK.
BoatIotSdkInit() MUST be called before any use of BoAT IoT SDK per process.
BoatIotSdkDeInit() MUST be called after use of BoAT IoT SDK.
@see BoatIotSdkInit()
@return This function doesn't return any thing.
*******************************************************************************/
void BoatIotSdkDeInit(void)
{
BUINT32 i;
for( i = 0; i < BOAT_MAX_WALLET_NUM; i++ )
{
BoatWalletUnload(i);
}
#if RPC_USE_LIBCURL == 1
curl_global_cleanup();
#endif
// For Multi-Thread Support: DeleteMutex Here
return;
}
/******************************************************************************
@brief Create BoAT wallet
Function: BoatWalletCreate()
This function creates a wallet or loads an existed persistent wallet.
A wallet is a configuration for blockchain parameters as well as context for
blockchain operations. There are 2 types of wallet. One is a one-time wallet,
which only exists in RAM and disappears once the device is powered down. The
other is a persistent wallet, which is saved in non-volatile memory for later
loading.
If the given <wallet_name_str> is NULL, a one-time wallet is created. Otherwise
a persistent wallet with the given name will be created or loaded. If no wallet
with the given name exists, a new persistent wallet will be created with the
name and immediately loaded into RAM. If a persistent wallet with the given
name exists, it will be loaded into RAM.
To create a one-time wallet, <wallet_name_str> MUST be NULL and a non-NULL
<wallet_config_ptr> MUST be specified.
To create a persistent wallet, <wallet_name_str>, <wallet_config_ptr> and
<wallet_config_size> MUST be specified. If a persitent wallet with the given
<wallet_name_str> exists, the specified configuration will overwrite the
existed one, both in RAM and in non-volatile memroy.
To load an existed persistent wallet into RAM, specify its name in <wallet_name_str>,
specify <wallet_config_ptr> = NULL and <wallet_config_size> = the configuration
size of the specified <protocol_type>.
To unload a wallet from RAM, which was loaded by BoatWalletCreate(), call
BoatWalletUnload(). For persisent wallet, this does NOT delete it from
non-volatile memory.
To delete a persistent wallet from non-volatile memroy, call BoatWalletDelete().
This does NOT unload it from RAM. If a loaded persistent wallet is deleted
without unloading it, it becomes a one-time wallet.
@see BoatWalletUnload() BoatWalletDelete()
@return
This function returns the non-negative index of the loaded wallet.\n
It returns -1 if wallet creation fails.
@param[in] protocol_type
The blockchain protocol. See boattypes.h for supported protocol.
@param[in] wallet_name_str
A string of wallet name.\n
If the given <wallet_name_str> is NULL, a one-time wallet is created.\n
Otherwise a persistent wallet with the given name will be created or loaded.
@param[in] wallet_config_ptr
Configuration (e.g. crypto key) for the wallet.\n
The exact configuration definition is determinted by the specified <protocol_type>.
@param[in] wallet_config_size
Size (in byte) of configuration specified by <wallet_config_ptr>.
*******************************************************************************/
BSINT32 BoatWalletCreate(BoatProtocolType protocol_type, const BCHAR *wallet_name_str, const void * wallet_config_ptr, BUINT32 wallet_config_size)
{
BSINT32 i;
BUINT8 loaded_wallet_config_array[wallet_config_size];
// Check wallet configuration
if( wallet_name_str == NULL && wallet_config_ptr == NULL )
{
BoatLog(BOAT_LOG_NORMAL, "Invalid wallet configuration.");
return -1;
}
// For Multi-Thread Support: ObtainMutex Here
for( i = 0; i < BOAT_MAX_WALLET_NUM; i++ )
{
if( g_boat_iot_sdk_context.wallet_list[i].is_used == BOAT_FALSE )
{
g_boat_iot_sdk_context.wallet_list[i].is_used = BOAT_TRUE;
break;
}
}
// For Multi-Thread Support: ReleaseMutex Here
if( i >= BOAT_MAX_WALLET_NUM )
{
BoatLog(BOAT_LOG_NORMAL, "Too many wallets was loaded.");
return -1;
}
if( wallet_name_str != NULL )
{
if( wallet_config_ptr != NULL )
{
// Create persistent wallet / Overwrite existed configuration
if( BOAT_SUCCESS != BoatPersistStore(wallet_name_str, wallet_config_ptr, wallet_config_size) )
{
return -1;
}
memcpy(loaded_wallet_config_array, wallet_config_ptr, wallet_config_size);
}
else
{
// Load persistent wallet;
if( BOAT_SUCCESS != BoatPersistRead(wallet_name_str, loaded_wallet_config_array, wallet_config_size) )
{
return -1;
}
}
}
else
{
memcpy(loaded_wallet_config_array, wallet_config_ptr, wallet_config_size);
}
// Check protocol type
g_boat_iot_sdk_context.wallet_list[i].protocol_type = protocol_type;
switch(protocol_type)
{
#if PROTOCOL_USE_ETHEREUM == 1
case BOAT_PROTOCOL_ETHEREUM:
g_boat_iot_sdk_context.wallet_list[i].wallet_ptr = BoatEthWalletInit((BoatEthWalletConfig*)loaded_wallet_config_array, wallet_config_size);
break;
#endif
#if PROTOCOL_USE_HLFABRIC == 1
case BOAT_PROTOCOL_HLFABRIC:
g_boat_iot_sdk_context.wallet_list[i].wallet_ptr = BoatHLFabricWalletInit((BoatHLFabricWalletConfig*)loaded_wallet_config_array, wallet_config_size);
break;
#endif
#if PROTOCOL_USE_PLATONE == 1
case BOAT_PROTOCOL_PLATONE:
g_boat_iot_sdk_context.wallet_list[i].wallet_ptr = BoatPlatoneWalletInit((BoatPlatoneWalletConfig*)loaded_wallet_config_array, wallet_config_size);
break;
#endif
default:
g_boat_iot_sdk_context.wallet_list[i].wallet_ptr = NULL;
}
if( g_boat_iot_sdk_context.wallet_list[i].wallet_ptr == NULL )
{
BoatLog(BOAT_LOG_NORMAL, "Fail to create wallet: protocol type: %d.", (BSINT32)protocol_type);
g_boat_iot_sdk_context.wallet_list[i].is_used = BOAT_FALSE;
return -1;
}
return i;
}
/******************************************************************************
@brief Unload a wallet
Function: BoatWalletUnload()
This function unloads a wallet from RAM if no more operations on this wallet
is required. If the wallet is of persistent type, this function will NOT
delete it from non-volatile memory. To delete a persistent wallet from
non-volatile memory, call BoatWalletDelete().
@see BoatWalletCreate() BoatWalletDelete()
@return This function doesn't return any thing.
@param[in] wallet_index
The wallet index to unload.
*******************************************************************************/
void BoatWalletUnload(BSINT32 wallet_index)
{
BoatProtocolType protocol;
if( wallet_index >= 0 && wallet_index < BOAT_MAX_WALLET_NUM
&& g_boat_iot_sdk_context.wallet_list[wallet_index].is_used != BOAT_FALSE
&& g_boat_iot_sdk_context.wallet_list[wallet_index].wallet_ptr != NULL )
{
protocol = g_boat_iot_sdk_context.wallet_list[wallet_index].protocol_type;
switch(protocol)
{
#if PROTOCOL_USE_ETHEREUM == 1
case BOAT_PROTOCOL_ETHEREUM:
BoatEthWalletDeInit(g_boat_iot_sdk_context.wallet_list[wallet_index].wallet_ptr);
break;
#endif
#if PROTOCOL_USE_HLFABRIC == 1
case BOAT_PROTOCOL_HLFABRIC:
BoatHLFabricWalletDeInit(g_boat_iot_sdk_context.wallet_list[wallet_index].wallet_ptr);
break;
#endif
#if PROTOCOL_USE_PLATONE == 1
case BOAT_PROTOCOL_PLATONE:
BoatPlatoneWalletDeInit(g_boat_iot_sdk_context.wallet_list[wallet_index].wallet_ptr);
break;
#endif
default:
BoatLog(BOAT_LOG_VERBOSE, "Unknown blockchain protocol type: %u.", protocol);
protocol = BOAT_PROTOCOL_UNKNOWN;
}
if( protocol != BOAT_PROTOCOL_UNKNOWN )
{
g_boat_iot_sdk_context.wallet_list[wallet_index].wallet_ptr = NULL;
g_boat_iot_sdk_context.wallet_list[wallet_index].is_used = BOAT_FALSE;
}
}
return;
}
/******************************************************************************
@brief Delete a persistent wallet
Function: BoatWalletDelete()
This function deletes a persistent wallet from non-volatile memory. This
does NOT unload it from RAM. If a loaded persistent wallet is deleted
without unloading it, it becomes a one-time wallet.
@see BoatWalletCreate() BoatWalletUnload()
@return This function doesn't return any thing.
@param[in] wallet_name_str
The wallet name to delete.
*******************************************************************************/
void BoatWalletDelete(BCHAR * wallet_name_str)
{
// Delete persistent wallet
BoatPersistDelete(wallet_name_str);
return;
}
/******************************************************************************
@brief Get the BoAT wallet context by index.
Function: BoatGetWalletByIndex()
This function gets the BoAT wallet context by index.
@return This function returns a pointer to the wallet context.
@param[in] wallet_index
The wallet index.
*******************************************************************************/
void * BoatGetWalletByIndex(BSINT32 wallet_index)
{
if( wallet_index >= 0 && wallet_index < BOAT_MAX_WALLET_NUM )
{
if( g_boat_iot_sdk_context.wallet_list[wallet_index].is_used != BOAT_FALSE
&& g_boat_iot_sdk_context.wallet_list[wallet_index].wallet_ptr != NULL )
{
return(g_boat_iot_sdk_context.wallet_list[wallet_index].wallet_ptr);
}
}
return NULL;
}
|
gitter-badger/BoAT-X-Framework | include/boatutility.h | /******************************************************************************
* Copyright (C) 2018-2021 aitos.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/*!@brief Header file for utility functions
@file
boatutility.h is header file for boatwallet utility functions.
*/
#ifndef __BOATUTILITY_H__
#define __BOATUTILITY_H__
#include "boatiotsdk.h"
//!@brief Argument type for UtilityTrimBin(), UtilityHex2Bin() and UtilityUint32ToBigend()
typedef enum
{
TRIMBIN_TRIM_NO, //!< Don't trim zeros
TRIMBIN_LEFTTRIM //!< Trim leading or MSB zeros
}TRIMBIN_TRIM_MODE;
//!@brief Argument type for UtilityHex2Bin()
typedef enum
{
BIN2HEX_LEFTTRIM_UNFMTDATA = 0, //!< Don't trim zeros !< Trim {0x00, 0x01, 0x00 0xAB} => "0x000100AB" or "000100AB"
BIN2HEX_LEFTTRIM_QUANTITY, //!< Trim {0x00, 0x01, 0x00 0xAB} => "0x100AB" or "100AB"
BIN2HEX_LEFTTRIM_TWOHEXPERBYTE //!< Trim {0x00, 0x01, 0x00 0xAB} => "0x0100AB" or "0100AB"
}BIN2HEX_TRIM_MODE;
//!@brief Argument type for UtilityBin2Hex()
typedef enum
{
BIN2HEX_PREFIX_0x_NO = 0, //<! Prepend "0x" to converted HEX string
BIN2HEX_PREFIX_0x_YES //<! Don't prepend "0x" to converted HEX string
}BIN2HEX_PREFIX_0x_MODE;
//!@brief A struct to maintain a dynamic length string.
typedef struct TStringWithLen
{
BCHAR *string_ptr; //!< address of the string storage
BUINT32 string_len; //!< string length in byte excluding NULL terminator, equal to strlen(string_ptr)
BUINT32 string_space;//!< size of the space <string_ptr> pointing to, including null terminator
}StringWithLen;
extern const BCHAR * const g_log_level_name_str[];
#if BOAT_LOG_LEVEL == BOAT_LOG_NONE
/*!@brief Log Output
@param level
Log priority level. One of BOAT_LOG_CRITICAL, BOAT_LOG_NORMAL or BOAT_LOG_VERBOSE.
@param format
Similar to that in printf().
*/
#define BoatLog(level, format,...)
#else
#define BoatLog(level, format,...)\
do{\
if( level <= BOAT_LOG_LEVEL ) {printf("%s: "__FILE__":%d, %s(): "format"\n", g_log_level_name_str[level-1], __LINE__, __func__, ##__VA_ARGS__);}\
}while(0)
#endif
/*!@brief Round value up to the nearest multiple of step
@param value
The value to round up
@param step
The step of round
*/
#define BOAT_ROUNDUP(value, step) ((((value) - 1)/(step) + 1) * (step))
/*!@brief Return the minimal value of two
@param value1
The first value to compare
@param value2
The second value to compare
*/
#define BOAT_MIN(value1, value2) ((value1) < (value2) ? (value1) : (value2))
/*!@brief Return the maximal value of two
@param value1
The first value to compare
@param value2
The second value to compare
*/
#define BOAT_MAX(value1, value2) ((value1) > (value2) ? (value1) : (value2))
#ifdef __cplusplus
extern "C" {
#endif
/*!*****************************************************************************
@brief Trim zeros of a binary stream
Function: UtilityTrimBin()
This function trims zeros of a binary stream and returns the length after
trimming. Currently only left trimming (i.e. trimming leading zeros) is
supported.
This function simply ignores leading zeros and copy the first non-zero byte
til the end of the stream to the target buffer. It doesn't treat the data
in buffer as integer, i.e. it doesn't care about the endian.
The source and target buffer may be overlapped.
For example, {0x00, 0x01, 0x02, 0x00} is trimed to {0x01, 0x02, 0x00} and
returns 3.
@return
This function returns how many bytes the trimmed binary stream is.
@param to_ptr
A buffer to contain the trimmed binary stream. Its size must be at
least <from_len> bytes. <to_ptr> and <from_ptr> may be overlapped.
@param from_ptr
The binary stream to trim. <to_ptr> and <from_ptr> may be overlapped.
@param from_len
Length of <from_ptr>.
@param trim_mode
Only TRIMBIN_LEFTTRIM is supported, i.e. trim leading zeros.\n
If TRIMBIN_TRIM_NO is specified, this function acts like memmove().
@param zero_as_null
In case the binary stream contains only one or multiple 0x00, if\n
<zero_as_null> is BOAT_TRUE, it will be treated as a null stream and\n
returns 0.\n
If <zero_as_null> is BOAT_FALSE, it will be trimed to a single 0x00 and\n
returns 1.\n
<zero_as_null> should be BOAT_TRUE for RLP-Encoding purpose.
*******************************************************************************/
BUINT32 UtilityTrimBin(
BOAT_OUT BUINT8 *to_ptr,
const BUINT8 *from_ptr,
BUINT32 from_len,
TRIMBIN_TRIM_MODE trim_mode,
BBOOL zero_as_null
);
/*!****************************************************************************
@brief Convert a binary stream to HEX string with optional leading zeros trimming and "0x" prefix
Function: UtilityBin2Hex()
This function converts a binary stream to a null-terminated HEX string.
Optionally leading zeros can be trimmed during conversion.
Optionally "0x" prefix can be prepended to the HEX string.
There is no space to delimit every HEX code.
The case of "a" through "f" is always lower case.
There are 3 ways to trim leading zeros. For example, a binary stream
{0x00, 0x01, 0x00, 0xAB} will be converted to string:
"000100ab" : if <trim_mode> = BIN2HEX_LEFTTRIM_UNFMTDATA
"100ab" : if <trim_mode> = BIN2HEX_LEFTTRIM_QUANTITY
"0100ab" : if <trim_mode> = BIN2HEX_LEFTTRIM_TWOHEXPERBYTE
Note that this function doesn't treat the binary stream as an integer and thus
it doens't make any endian conversion.
@return
This function returns the length of the converted HEX string excluding NULL\n
terminator. It equals to strlen of the string.\n
If <to_str> is NULL, this function does nothing and returns 0.\n
If <from_len> is 0 or <from_ptr> is NULL, and <to_str> is NOT NULL, this\n
function writes a '\0' to <to_str>, i.e. a NULL string and returns 0.
@param[out] to_str
The buffer to hold the converted HEX string.\n
Its size should be least <from_len>*2+1 bytes if <prefix_0x_mode>=BIN2HEX_PREFIX_0x_NO,\n
or <from_len>*2+3 bytes if <prefix_0x_mode>=BIN2HEX_PREFIX_0x_YES.\n
If <to_str> is NULL, this function does nothing and returns 0.
@param[in] from_ptr
The binary stream to convert from.\n
If <from_ptr> is NULL and <to_str> is NOT NULL, this function writes a\n
'\0' to <to_str>, i.e. a NULL string and returns 1.
@param[in] from_len
The length of <from_ptr> in byte.\n
If <from_len> is 0 and <to_str> is NOT NULL, this function writes a\n
'\0' to <to_str>, i.e. a NULL string and returns 1.
@param[in] trim_mode
BIN2HEX_LEFTTRIM_UNFMTDATA to trim as unformatted data;\n
BIN2HEX_LEFTTRIM_QUANTITY to trim as a quantity;\n
BIN2HEX_LEFTTRIM_TWOHEXPERBYTE to two hex digits per byte
@param[in] prefix_0x_mode
BIN2HEX_PREFIX_0x_YES: Prepend a "0x" prefix at the beginning of the HEX string;\n
BIN2HEX_PREFIX_0x_NO: Don't prepend "0x" prefix.
@param[in] zero_as_null
In case the binary stream contains only one or multiple 0x00, if\n
<zero_as_null> is BOAT_TRUE, it will be converted to a null sting and\n
returns 0.\n
If <zero_as_null> is BOAT_FALSE, it will be converted to "0" or "00"\n
according to <trim_mode>.\n
<zero_as_null> should be BOAT_TRUE for RLP-Encoding purpose.
*******************************************************************************/
BUINT32 UtilityBin2Hex(
BOAT_OUT BCHAR *to_str,
const BUINT8 *from_ptr,
BUINT32 from_len,
BIN2HEX_TRIM_MODE trim_mode,
BIN2HEX_PREFIX_0x_MODE prefix_0x_mode,
BBOOL zero_as_null
);
/*!*****************************************************************************
@brief Convert a HEX string to binary stream with optional leading zeros trimming
Function: UtilityHex2Bin()
Description:
This function converts a HEX string to a binary stream.
Optionally leading zeros can be trimmed during conversion.
If there is "0x" prefix at the beginning of the HEX string, it's ignored.
There should be no space between HEX codes.
If <to_size> is too small to hold the converted binary stream, only the
beginning <to_size> bytes are converted and written to <to_ptr>.
The trim_mode is the same as UtilityTrimBin(). Odd length of HEX string is
allowed as if it were left filled with a "0". For example, a HEX string
"0x00123ab" is treated as "0x000123ab" and converted to:
{0x01, 0x23, 0xab}: if <trim_mode> = TRIMBIN_LEFTTRIM;
{0x00, 0x01, 0x23, 0xab}: if <trim_mode> = TRIMBIN_TRIM_NO
Note that this function doesn't treat the HEX string as an integer and thus
it doens't make any endian conversion.
@see UtilityTrimBin()
@return
This function returns how many bytes the converted binary stream is if the\n
conversion completes successfully. If the output buffer is too small to\n
hold the converted binary stream, it returns <to_size>.\n
If any non-HEX character is encountered, or <from_str> is an all-zero HEX\n
string and <trim_mode> is TRIMBIN_LEFTTRIM, it returns 0.
@param[out] to_ptr
The buffer to hold the converted binary stream.
@param[in] to_size
The size of <to_ptr> in bytes.\n
It's safe to ensure <to_size> >= (strlen(from_str)+1)/2 bytes.\n
@param[in] from_str
The null-terminated HEX string to convert from. "0x" prefix is optional\n
and ignored. There should be no space between HEX codes.
@param[in] trim_mode
TRIMBIN_LEFTTRIM: Trim leading zeros;\n
TRIMBIN_TRIM_NO: Don't trim.
@param[in] zero_as_null
In case the HEX string contains only one or multiple "00" and <trim_mode>\n
is TRIMBIN_LEFTTRIM, if <zero_as_null> is BOAT_TRUE, nothing will be\n
written to <to_ptr> and it returns 0.\n
If <zero_as_null> is BOAT_FALSE, it will be converted to a single 0x00\n
and returns 1.\n
<zero_as_null> should be BOAT_TRUE for RLP-Encoding purpose.
*******************************************************************************/
BUINT32 UtilityHex2Bin(
BOAT_OUT BUINT8 *to_ptr,
BUINT32 to_size,
const BCHAR *from_str,
TRIMBIN_TRIM_MODE trim_mode,
BBOOL zero_as_null
);
/*!*****************************************************************************
@brief Convert a host endian BUINT32 to bigendian with optional MSB zeros trimming
Function: UtilityUint32ToBigend()
This function converts a host endian (typically littleendian) BUINT32 integer
to bigendian.
Optionally most siganificant zeros can be trimmed during conversion.
The trim_mode is the same as UtilityTrimBin(). For example, a BUINT32 integer
0x000123ab is converted to:
{0x01, 0x23, 0xab}: if <trim_mode> = TRIMBIN_LEFTTRIM;
{0x00, 0x01, 0x23, 0xab}: if <trim_mode> = TRIMBIN_TRIM_NO
@see UtilityTrimBin()
@return
This function returns how many bytes the converted bigendian integer is.\n
If <trim_mode> = TRIMBIN_TRIM_NO, it always returns 4.
@param[out] to_big_ptr
The buffer to hold the converted binary stream.
@param[in] from_host_integer
The host endian BUINT32 integer to convert.
@param[in] trim_mode
TRIMBIN_LEFTTRIM: Trim MSB zeros;\n
TRIMBIN_TRIM_NO: Don't trim.
*******************************************************************************/
BUINT8 UtilityUint32ToBigend(
BOAT_OUT BUINT8 *to_big_ptr,
BUINT32 from_host_integer,
TRIMBIN_TRIM_MODE trim_mode
);
/*!*****************************************************************************
@brief Convert a host endian BUINT64 to bigendian with optional MSB zeros trimming
Function: UtilityUint64ToBigend()
This function converts a host endian (typical littleendian) BUINT64 integer
to bigendian.
Optionally most siganificant zeros can be trimmed during conversion.
It's a 64-bit version of UtilityUint32ToBigend().
@see UtilityUint32ToBigend() UtilityTrimBin()
@return
This function returns how many bytes the converted bigendian integer is.\n
If <trim_mode> = TRIMBIN_TRIM_NO, it always returns 8.
@param[out] to_big_ptr
The buffer to hold the converted binary stream.
@param[in] from_host_integer
The host endian BUINT64 integer to convert.
@param[in] trim_mode
TRIMBIN_LEFTTRIM: Trim MSB zeros;\n
TRIMBIN_TRIM_NO: Don't trim.
*******************************************************************************/
BUINT8 UtilityUint64ToBigend(
BOAT_OUT BUINT8 *to_big_ptr,
BUINT64 from_host_integer,
TRIMBIN_TRIM_MODE trim_mode
);
/*!*****************************************************************************
@brief Change endianness
Function: UtilityChangeEndian()
This function changes a value's endianness. It simply swaps Byte[0] and
Byte[n-1], Byte[1] and Byte[n-2]...
@return
This function returns the pointer of the converted value.
If <value_ptr> is NULL, it returns NULL.
@param[inout] value_ptr
The value to change endianness.
@param[in] value_len
Size (in byte) of <value_ptr>.
*******************************************************************************/
void * UtilityChangeEndian(BOAT_INOUT void *value_ptr, BUINT32 value_len);
/*!*****************************************************************************
@brief Convert a host endian BUINT32 to bigendian
Function: Utilityhtonl()
This function converts a host endian (typically littleendian) BUINT32 integer
to bigendian.
@see UtilityUint32ToBigend()
@return
This function returns the converted bigendian BUINT32 integer.
@param[in] from_host_integer
The host endian BUINT32 integer to convert.
*******************************************************************************/
BUINT32 Utilityhtonl(BUINT32 from_host_integer);
/*!*****************************************************************************
@brief Convert a bigendian BUINT32 to host endian
Function: Utilityhtonl()
This function converts a bigendian BUINT32 integer to host endian (typically
littleendian).
@see Utilityhtonl()
@return
This function returns the converted host endian BUINT32 integer.
@param[in] from_big_integer
The big endian BUINT32 integer to convert.
*******************************************************************************/
BUINT32 Utilityntohl(BUINT32 from_host_integer);
/*!*****************************************************************************
@brief Convert a string representing wei in HEX to ether in double float
Function: UtilityWeiStrToEthDouble()
This function converts a string representing wei in HEX to ether in double
float.
1 ether is 1e18 wei. Note that in Ethereum an integer type is up to 256 bits
while most C compilers natively support up to 64-bit integer. A 64-bit
unsigned interger can represent up to 2^64 - 1, which is roughly 1.845e19.
Thus it's not possible to convert more than 1.845e19 wei (i.e. 18.45 ether)
to native integer type.
Converting integer type wei to double float type ether loses pricision.
Fortunately the unit of ether is usually for friendly human-reading only
and slight pricision loss is not a problem.
@return
This function returns the converted ether in double float.
@param[in] wei_str
The HEX-represented string of wei, either in "0xabcd..." or "abcd..." format.
*******************************************************************************/
double UtilityWeiStrToEthDouble(const BCHAR *wei_str);
/*!*****************************************************************************
@brief Wrapper function for memory allocation
Function: BoatMalloc()
This function is a wrapper for dynamic memory allocation.
It typically wraps malloc() in a linux or Windows system.
For RTOS it depends on the specification of the RTOS.
@return
This function returns the address of the allocated memory. If allocation\n
fails, it returns NULL.
@param[in] size
How many bytes to allocate.
*******************************************************************************/
void *BoatMalloc(BUINT32 size);
/*!*****************************************************************************
@brief Wrapper function for memory allocation
Function: BoatFree()
This function is a wrapper for dynamic memory de-allocation.
It typically wraps free() in a linux or Windows system.
For RTOS it depends on the specification of the RTOS.
@see BoatMalloc()
@return
This function doesn't return anything.
@param[in] mem_ptr
The address to free. The address must be the one returned by BoatMalloc().
*******************************************************************************/
void BoatFree(void *mem_ptr);
/*!*****************************************************************************
@brief Wrapper function for sleep (thread suspension)
Function: BoatSleep()
This function is a wrapper for sleep (thread suspension).
It typically wraps sleep() or usleep() in a linux or Windows system.
For RTOS it depends on the specification of the RTOS.
@return
This function doesn't return anything.
@param[in] second
How many seconds to sleep.
*******************************************************************************/
void BoatSleep(BUINT32 second);
#ifdef __cplusplus
}
#endif /* end of __cplusplus */
#endif
|
gitter-badger/BoAT-X-Framework | sdk/rpc/curlport.h | <gh_stars>1-10
/******************************************************************************
* Copyright (C) 2018-2021 aitos.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/*!@brief libcurl porting header file
@file
curlport.h is the header file of libcurl porting of RPC.
DO NOT call functions in this file directly. Instead call wrapper functions
provided by rpcport.
To use libcurl porting, RPC_USE_LIBCURL in boatoptions.h must set to 1.
*/
#ifndef __CURLPORT_H__
#define __CURLPORT_H__
#if RPC_USE_LIBCURL == 1
#include "boatinternal.h"
//!The step to dynamically expand the receiving buffer.
#define CURLPORT_RECV_BUF_SIZE_STEP 1024
typedef struct TCurlPortContext
{
BCHAR *remote_url_str; //!< URL of the blockchain node, e.g. "http://a.b.com:8545"
StringWithLen curlport_response; //!< Store response from remote peer
}CurlPortContext;
#ifdef __cplusplus
extern "C" {
#endif
CurlPortContext * CurlPortInit(void);
void CurlPortDeinit(CurlPortContext * curlport_context_ptr);
BOAT_RESULT CurlPortSetOpt(CurlPortContext * curlport_context_ptr, BCHAR *remote_url_str);
BOAT_RESULT CurlPortRequestSync(CurlPortContext * curlport_context_ptr,
const BCHAR *request_str,
BUINT32 request_len,
BOAT_OUT BCHAR **response_str_ptr,
BOAT_OUT BUINT32 *response_len_ptr);
#ifdef __cplusplus
}
#endif /* end of __cplusplus */
#endif // end of #if RPC_USE_LIBCURL == 1
#endif
|
gitter-badger/BoAT-X-Framework | tests/testcommon.h | /******************************************************************************
* Copyright (C) 2018-2021 aitos.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "boatiotsdk.h"
#define BoatDisplayTestResult(is_pass, case_name_str) \
{\
if( is_pass ) \
{ \
BoatLog(BOAT_LOG_NORMAL, "%s Passed.\n", (case_name_str)); \
} \
else \
{ \
BoatLog(BOAT_LOG_NORMAL, "%s Failed.\n", (case_name_str)); \
return BOAT_ERROR; \
} \
}
#define BoatDisplayCellTestResult(result_num,cell_is_pass,case_cell_name_str) \
{\
if( cell_is_pass ) \
{ \
BoatLog(BOAT_LOG_NORMAL, "%s Passed.\n", (case_cell_name_str)); \
} \
else \
{ \
result_num--;\
BoatLog(BOAT_LOG_NORMAL, "%s Failed.\n", (case_cell_name_str)); \
} \
}
typedef struct TBoatIotSdkTest{
BCHAR gasprice_str[32]; //gasprice
BCHAR gaslimit_str[32]; //gaslimit
BCHAR contract_addr_str[64]; //Contract Address
BCHAR recipient_addr_str[64]; //Recipient Address
BCHAR priv_key_str[64]; //Private Key
BCHAR node_url_str[127]; //node url
BCHAR wallet_name_str[127]; //Wallet name
BoatProtocolType protocol_use; //platone
} BoatIotSdkTest;
|
gitter-badger/BoAT-X-Framework | tests/case_11_eth_cov.c | /******************************************************************************
* Copyright (C) 2018-2021 aitos.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "boatiotsdk.h"
#include "boatethereum.h"
#include "web3intf.h"
#include "testcommon.h"
#define TEST_ETH_PRIVATE_KEYCOV_0 "0x1234567812345678123456781234567812345678123456781234567812345678"
#define TEST_ETH_NODE_URLCOV_0 "HTTP://127.0.0.1:7545"
#define TEST_ETH_WALLET_NAMECOV_0 "./tests/eth.key"
BoatEthWallet *g_case_30_ethereum_wallet_ptr;
BoatEthWallet *wallet_ptr;
BOAT_RESULT Case_EthereumPreCondition(BSINT8 *wallet_num)
{
BSINT32 index;
BoatEthWalletConfig wallet_config;
BoatEthWallet *wallet_ptr;
// Set Private Key
UtilityHex2Bin( wallet_config.priv_key_array,
32,
TEST_ETH_PRIVATE_KEYCOV_0,
TRIMBIN_TRIM_NO,
BOAT_FALSE);
wallet_config.chain_id = 1;
wallet_config.eip155_compatibility = 0;
// Set Node URL
wallet_config.node_url_str[BOAT_NODE_URL_MAX_LEN-1] = '\0';
strncpy(wallet_config.node_url_str, TEST_ETH_NODE_URLCOV_0, BOAT_NODE_URL_MAX_LEN-1);
// Test one-time wallet
index = BoatWalletCreate(BOAT_PROTOCOL_ETHEREUM, NULL, &wallet_config, sizeof(BoatEthWalletConfig));
if( index == -1 )
{
BoatLog(BOAT_LOG_NORMAL, "Fail to create wallet.");
return BOAT_ERROR;
}
wallet_ptr = BoatGetWalletByIndex(index);
g_case_30_ethereum_wallet_ptr = wallet_ptr;
*wallet_num = index;
return BOAT_SUCCESS;
}
BOAT_RESULT Case_EthereumPreCondition_A(BSINT8 *wallet_num)
{
BSINT32 index;
BoatEthWalletConfig wallet_config;
BoatEthWallet *wallet_ptr;
// Set Private Key
UtilityHex2Bin( wallet_config.priv_key_array,
32,
TEST_ETH_PRIVATE_KEYCOV_0,
TRIMBIN_TRIM_NO,
BOAT_FALSE);
wallet_config.chain_id = 1;
wallet_config.eip155_compatibility = 0;
// Set Node URL
wallet_config.node_url_str[BOAT_NODE_URL_MAX_LEN-1] = '\0';
strncpy(wallet_config.node_url_str, TEST_ETH_NODE_URLCOV_0, BOAT_NODE_URL_MAX_LEN-1);
// Create a new wallet or overwrite an existed wallet
index = BoatWalletCreate(BOAT_PROTOCOL_ETHEREUM, TEST_ETH_WALLET_NAMECOV_0, &wallet_config, sizeof(BoatEthWalletConfig));
if( index == -1 )
{
BoatLog(BOAT_LOG_NORMAL, "Fail to create wallet.");
return BOAT_ERROR;
}
wallet_ptr = BoatGetWalletByIndex(index);
g_case_30_ethereum_wallet_ptr = wallet_ptr;
*wallet_num = index;
return BOAT_SUCCESS;
}
BOAT_RESULT Case_EthereumPreCondition_B(BSINT8 *wallet_num)
{
BSINT32 index;
BoatEthWalletConfig wallet_config;
BoatEthWallet *wallet_ptr;
// Set Private Key
UtilityHex2Bin( wallet_config.priv_key_array,
32,
TEST_ETH_PRIVATE_KEYCOV_0,
TRIMBIN_TRIM_NO,
BOAT_FALSE);
wallet_config.chain_id = 1;
wallet_config.eip155_compatibility = 0;
// Set Node URL
wallet_config.node_url_str[BOAT_NODE_URL_MAX_LEN-1] = '\0';
strncpy(wallet_config.node_url_str, TEST_ETH_NODE_URLCOV_0, BOAT_NODE_URL_MAX_LEN-1);
index = BoatWalletCreate(BOAT_PROTOCOL_ETHEREUM, TEST_ETH_WALLET_NAMECOV_0, NULL, sizeof(BoatEthWalletConfig));
if( index == -1 )
{
BoatLog(BOAT_LOG_NORMAL, "Fail to create wallet.");
return BOAT_ERROR;
}
wallet_ptr = BoatGetWalletByIndex(index);
g_case_30_ethereum_wallet_ptr = wallet_ptr;
*wallet_num = index;
return BOAT_SUCCESS;
}
BOAT_RESULT Case_utilitiesMain()
{
BOAT_RESULT result=BOAT_SUCCESS;
BUINT8 from_ptr_A1[10]={0,1,2,3,4,5,6,7,8,9};
BoatDisplayCellTestResult(result, 0 == UtilityTrimBin(NULL,from_ptr_A1,10,TRIMBIN_TRIM_NO,BOAT_FALSE), "UtilityTrimBin");
BUINT8 from_ptr_A2[10]={0};
BUINT8 to_ptr[16];
BoatDisplayCellTestResult(result, 10 == UtilityTrimBin(to_ptr,from_ptr_A2,10,TRIMBIN_TRIM_NO,BOAT_FALSE), "UtilityTrimBin");
BoatDisplayCellTestResult(result, 1 == UtilityTrimBin(to_ptr,from_ptr_A2,10,TRIMBIN_LEFTTRIM,BOAT_FALSE), "UtilityTrimBin");
BCHAR to_ptr1[16];
BoatDisplayCellTestResult(result, 3 == UtilityBin2Hex(to_ptr1,from_ptr_A2,10,BIN2HEX_LEFTTRIM_QUANTITY,BIN2HEX_PREFIX_0x_YES,BOAT_FALSE), "UtilityBin2Hex");
BUINT8 from_ptr_A3[10]={0,1,2,3};
BoatDisplayCellTestResult(result, 19 == UtilityBin2Hex(to_ptr1,from_ptr_A3,10,BIN2HEX_LEFTTRIM_QUANTITY,BIN2HEX_PREFIX_0x_YES,BOAT_FALSE), "UtilityBin2Hex");
BUINT8 from_ptr_A4[10]={0x00,0x01,2,3};
BoatDisplayCellTestResult(result, 19 == UtilityBin2Hex(to_ptr1,from_ptr_A4,10,BIN2HEX_LEFTTRIM_QUANTITY,BIN2HEX_PREFIX_0x_YES,BOAT_FALSE), "UtilityBin2Hex");
BCHAR from_ptr_A5[10]="0x123456";
BoatDisplayCellTestResult(result, 3 == UtilityHex2Bin(to_ptr,strlen(from_ptr_A5),from_ptr_A5,TRIMBIN_LEFTTRIM,BOAT_FALSE), "UtilityHex2Bin");
BCHAR from_ptr_A6[10]="0x000000";
BoatDisplayCellTestResult(result, 1 == UtilityHex2Bin(to_ptr,strlen(from_ptr_A6),from_ptr_A6,TRIMBIN_LEFTTRIM,BOAT_FALSE), "UtilityHex2Bin");
BUINT8 to_big_ptr_A1[16]={0};
BUINT32 from_host_integer_A1=0;
BoatDisplayCellTestResult(result, 1 == UtilityUint32ToBigend(to_big_ptr_A1,from_host_integer_A1,TRIMBIN_LEFTTRIM), "UtilityUint32ToBigend");
BUINT64 big_num_A1=0x1234;
BoatDisplayCellTestResult(result, 2 == UtilityUint64ToBigend(to_big_ptr_A1,big_num_A1,TRIMBIN_LEFTTRIM), "UtilityUint64ToBigend");
BUINT64 big_num_A2=0;
BoatDisplayCellTestResult(result, 8 == UtilityUint64ToBigend(to_big_ptr_A1,big_num_A2,TRIMBIN_TRIM_NO), "UtilityUint64ToBigend");
BoatDisplayCellTestResult(result, 1 == UtilityUint64ToBigend(to_big_ptr_A1,big_num_A2,TRIMBIN_LEFTTRIM), "UtilityUint64ToBigend");
BUINT32 integer_A1=0x1234;
BoatDisplayCellTestResult(result, 0x34120000 == Utilityhtonl(integer_A1), "Utilityhtonl");
BoatDisplayCellTestResult(result, 0x34120000 == Utilityntohl(integer_A1), "Utilityntohl");
BoatDisplayCellTestResult(result, 1.0 == UtilityWeiStrToEthDouble("0xDE0B6B3A7640000"), "UtilityWeiStrToEthDouble");
return result;
}
//api_ethereum.c
BOAT_RESULT Case_apiethereumMain(BoatEthWallet *wallet_ptr)
{
BOAT_RESULT result=BOAT_SUCCESS;
BoatDisplayCellTestResult(result, NULL == BoatEthWalletInit(NULL, 0), "BoatEthWalletInit");
BoatDisplayCellTestResult(result, -108 == BoatEthWalletSetNodeUrl(NULL, TEST_ETH_NODE_URLCOV_0), "BoatEthWalletSetNodeUrl");
BoatDisplayCellTestResult(result, BOAT_SUCCESS != BoatEthWalletSetNodeUrl(wallet_ptr, NULL), "BoatEthWalletSetNodeUrl");
BoatDisplayCellTestResult(result, -108 == BoatEthWalletSetEIP155Comp(NULL, 1), "BoatEthWalletSetNodeUrl");
BoatDisplayCellTestResult(result, -108 == BoatEthWalletSetChainId(NULL, 1), "BoatEthWalletSetChainId");
BoatDisplayCellTestResult(result, NULL == BoatEthWalletGetBalance(NULL, NULL), "BoatEthWalletGetBalance");
BoatDisplayCellTestResult(result, NULL != BoatEthWalletGetBalance(wallet_ptr, "0x39631C55F60C708406Aa7b98AcDBfdDe2cC80157"), "BoatEthWalletGetBalance");
BoatEthTx tx_ptr;
BoatDisplayCellTestResult(result, BOAT_SUCCESS != BoatEthTxInit(NULL,&tx_ptr,true,"0x1234","0x333333","0x39631C55F60C708406Aa7b98AcDBfdDe2cC80157"), "BoatEthTxInit");
BoatDisplayCellTestResult(result, BOAT_SUCCESS == BoatEthTxInit(wallet_ptr,&tx_ptr,true,"0x1234","0x333333","0x39631C55F60C708406Aa7b98AcDBfdDe2cC80157"), "BoatEthTxInit");
BoatDisplayCellTestResult(result, BOAT_SUCCESS != BoatEthTxSetNonce(NULL, 0x23), "BoatEthTxSetNonce");
BoatDisplayCellTestResult(result, BOAT_SUCCESS != BoatEthTxSetGasPrice(NULL, NULL), "BoatEthTxSetGasPrice");
BoatDisplayCellTestResult(result, BOAT_SUCCESS == BoatEthTxSetGasPrice(&tx_ptr, NULL), "BoatEthTxSetGasPrice");
BoatDisplayCellTestResult(result, BOAT_SUCCESS != BoatEthTxSetGasLimit(NULL, NULL), "BoatEthTxSetGasLimit");
BoatDisplayCellTestResult(result, BOAT_SUCCESS != BoatEthTxSetGasLimit(&tx_ptr, NULL), "BoatEthTxSetGasLimit");
BUINT8 setrecipient[20]={0x12,0x13};
BoatDisplayCellTestResult(result, BOAT_SUCCESS != BoatEthTxSetRecipient(NULL, setrecipient), "BoatEthTxSetRecipient");
BoatDisplayCellTestResult(result, BOAT_SUCCESS != BoatEthTxSetValue(NULL, NULL), "BoatEthTxSetValue");
BoatDisplayCellTestResult(result, BOAT_SUCCESS != BoatEthTxSetData(NULL, NULL), "BoatEthTxSetData");
BoatDisplayCellTestResult(result, BOAT_SUCCESS != BoatEthTxSend(NULL), "BoatEthTxSend");
BoatDisplayCellTestResult(result, NULL == BoatEthCallContractFunc( NULL,NULL, NULL, 16), "BoatEthCallContractFunc");
tx_ptr.wallet_ptr = wallet_ptr;
BoatDisplayCellTestResult(result, NULL == BoatEthCallContractFunc( &tx_ptr,NULL, NULL, 16), "BoatEthCallContractFunc");
BoatDisplayCellTestResult(result, BOAT_ERROR == BoatEthGetTransactionReceipt(NULL), "BoatEthGetTransactionReceipt");
return result;
}
//boatethereum.c
BOAT_RESULT Case_boatethereumMain(BoatEthWallet *wallet_ptr)
{
BUINT32 result=BOAT_SUCCESS;
BoatDisplayCellTestResult(result, -108 == EthSendRawtx( NULL ), "EthSendRawtx");
BoatEthTx tx_toeth;
BoatDisplayCellTestResult(result, BOAT_SUCCESS == BoatEthTxInit(wallet_ptr, &tx_toeth, BOAT_TRUE,NULL,"0x333333","0xEF5D6d9D037Faa6493637E26A2B5d604f7722779"), "BoatEthTxInit");
BoatDisplayCellTestResult(result, BOAT_SUCCESS == BoatEthTxSetNonce(&tx_toeth, BOAT_ETH_NONCE_AUTO), "BoatEthTxSetNonce");
BoatFieldMax32B value;
BoatDisplayCellTestResult(result, BOAT_SUCCESS <= (value.field_len = UtilityHex2Bin(value.field,32, "0x00",TRIMBIN_LEFTTRIM, BOAT_TRUE )), "UtilityHex2Bin");
BoatDisplayCellTestResult(result, BOAT_SUCCESS == BoatEthTxSetValue(&tx_toeth, &value), "BoatEthTxSetValue");
BoatDisplayCellTestResult(result, BOAT_SUCCESS == BoatEthTxSetData(&tx_toeth, NULL), "BoatEthTxSetData");
BoatDisplayCellTestResult(result, BOAT_SUCCESS == BoatEthTxSend(&tx_toeth), "BoatEthTxSend");
return result;
}
BOAT_RESULT Case_web3Main(void)
{
BOAT_RESULT result=BOAT_SUCCESS;
Web3IntfContext *web3_init_A1;
web3_init_A1 = web3_init();
BoatDisplayCellTestResult(result, NULL != web3_init(), "web3_init");
web3_deinit(NULL);
BoatDisplayCellTestResult(result, NULL == web3_eth_getTransactionCount(NULL,NULL,NULL), "web3_eth_getTransactionCount");
BoatDisplayCellTestResult(result, NULL == web3_eth_getTransactionCount(web3_init_A1,NULL,NULL), "web3_eth_getTransactionCount");
BoatDisplayCellTestResult(result, NULL == web3_eth_gasPrice(NULL,NULL), "web3_eth_gasPrice");
BoatDisplayCellTestResult(result, NULL == web3_eth_getBalance(NULL,NULL,NULL), "web3_eth_getBalance");
BoatDisplayCellTestResult(result, NULL == web3_eth_sendRawTransaction(NULL,NULL,NULL), "web3_eth_sendRawTransaction");
BoatDisplayCellTestResult(result, NULL == web3_eth_sendRawTransaction(web3_init_A1,NULL,NULL), "web3_eth_sendRawTransaction");
BoatDisplayCellTestResult(result, NULL == web3_eth_getStorageAt(NULL,NULL,NULL), "web3_eth_getStorageAt");
BoatDisplayCellTestResult(result, NULL == web3_eth_getStorageAt(web3_init_A1,NULL,NULL), "web3_eth_getStorageAt");
Param_eth_getStorageAt param_ptr_A1;
param_ptr_A1.address_str="0x123456789";
param_ptr_A1.block_num_str="10";
param_ptr_A1.position_str="11";
BoatDisplayCellTestResult(result, NULL == web3_eth_getStorageAt(web3_init_A1,TEST_ETH_NODE_URLCOV_0,¶m_ptr_A1), "web3_eth_getStorageAt");
BoatDisplayCellTestResult(result, NULL == web3_eth_getTransactionReceiptStatus(NULL,NULL,NULL), "web3_eth_getTransactionReceiptStatus");
BoatDisplayCellTestResult(result, NULL == web3_eth_getTransactionReceiptStatus(web3_init_A1,NULL,NULL), "web3_eth_getTransactionReceiptStatus");
BoatDisplayCellTestResult(result, NULL == web3_eth_call(NULL,NULL,NULL), "web3_eth_call");
BoatDisplayCellTestResult(result, NULL == web3_eth_call(web3_init_A1,NULL,NULL), "web3_eth_call");
web3_deinit(web3_init_A1);
return BOAT_SUCCESS;
}
BOAT_RESULT Case_11_EthCovMain(void)
{
BOAT_RESULT case_result = BOAT_SUCCESS;
BSINT8 wallet_num=0;
case_result += Case_utilitiesMain();
case_result += Case_web3Main();
case_result += Case_EthereumPreCondition(&wallet_num);
case_result += Case_apiethereumMain(g_case_30_ethereum_wallet_ptr);
BoatWalletUnload(wallet_num);
g_case_30_ethereum_wallet_ptr = NULL;
case_result += Case_EthereumPreCondition_A(&wallet_num);
case_result += Case_boatethereumMain(g_case_30_ethereum_wallet_ptr);
BoatWalletUnload(wallet_num);
case_result += Case_EthereumPreCondition_B(&wallet_num);
BoatWalletUnload(wallet_num);
BoatLog(BOAT_LOG_NORMAL, "Case_11_EthCovMain case_result: %d.", case_result);
return case_result;
}
|
gitter-badger/BoAT-X-Framework | sdk/protocol/boatethereum.h | <reponame>gitter-badger/BoAT-X-Framework
/******************************************************************************
* Copyright (C) 2018-2021 aitos.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/*!@brief Header file for performing RAW transaction
@file
boatethereum.h is header file for RAW transaction construction and performing.
*/
#ifndef __BOATETHEREUM_H__
#define __BOATETHEREUM_H__
#include "boatinternal.h"
#ifdef __cplusplus
extern "C" {
#endif
BOAT_RESULT EthSendRawtx(BOAT_INOUT BoatEthTx *tx_ptr);
BOAT_RESULT EthSendRawtxWithReceipt(BOAT_INOUT BoatEthTx *tx_ptr);
#ifdef __cplusplus
}
#endif /* end of __cplusplus */
#endif
|
gitter-badger/BoAT-X-Framework | sdk/protocol/common/web3intf.h | /******************************************************************************
* Copyright (C) 2018-2021 aitos.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/*!@brief Web3 interface header file
@file
web3intf.h is the header file for web3 interface.
*/
#ifndef __WEB3INTF_H__
#define __WEB3INTF_H__
//!@brief step size of the buffer to store RPC "REQUEST/RESPONSE" string and RPC "result" string.
#define WEB3_STRING_BUF_STEP_SIZE 1024
typedef struct TWeb3IntfContext
{
void * rpc_context_ptr; //!< The RPC context. The exact type depends on the RPC method
BUINT32 web3_message_id; //!< Random Message ID to distinguish different messages.
BoatFieldVariable web3_json_string_buf; //!< A JSON string buffer used for both REQUEST and RESPONSE
BoatFieldVariable web3_result_string_buf; //!< A string buffer to store RPC "result" string parsed from JSON RESPONSE
}Web3IntfContext;
#ifdef __cplusplus
extern "C" {
#endif
BOAT_RESULT web3_parse_json_result(const BCHAR * json_string,
const BCHAR * child_name,
BoatFieldVariable *result_out);
Web3IntfContext * web3_init(void);
void web3_deinit(Web3IntfContext *web3intf_context_ptr);
//!@brief Parameter for web3_eth_getTransactionCount()
typedef struct TParam_eth_getTransactionCount
{
BCHAR *address_str; //!< String of 20-byte Ethereum address, e.g. "0x123456..."
BCHAR *block_num_str; //!< String of either block number or one of "latest", "earliest" and "pending"
}Param_eth_getTransactionCount;
BCHAR *web3_eth_getTransactionCount(Web3IntfContext *web3intf_context_ptr,
BCHAR *node_url_str,
const Param_eth_getTransactionCount *param_ptr);
//!@brief Parameter for web3_eth_getBalance()
typedef struct TParam_eth_getBalance
{
BCHAR *address_str; //!< String of 20-byte Ethereum address, e.g. "0x123456..."
BCHAR *block_num_str; //!< String of either block number or one of "latest", "earliest" and "pending"
}Param_eth_getBalance;
BCHAR *web3_eth_getBalance(Web3IntfContext *web3intf_context_ptr,
BCHAR *node_url_str,
const Param_eth_getBalance *param_ptr);
//!@brief Parameter for web3_eth_sendRawTransaction()
typedef struct TParam_eth_sendRawTransaction
{
BCHAR *signedtx_str; //!< String of the signed transaction in HEX with "0x" prefixed
}Param_eth_sendRawTransaction;
BCHAR *web3_eth_sendRawTransaction(Web3IntfContext *web3intf_context_ptr,
BCHAR *node_url_str,
const Param_eth_sendRawTransaction *param_ptr);
BCHAR *web3_eth_gasPrice(Web3IntfContext *web3intf_context_ptr, BCHAR *node_url_str);
//!@brief Parameter for web3_eth_getStorageAt()
typedef struct TParam_eth_getStorageAt
{
BCHAR *address_str; //!< String of 20-byte Ethereum address, e.g. "0x123456..."
BCHAR *position_str; //!< String of storage position
BCHAR *block_num_str; //!< String of either block number or one of "latest", "earliest" and "pending"
}Param_eth_getStorageAt;
BCHAR *web3_eth_getStorageAt(Web3IntfContext *web3intf_context_ptr,
BCHAR *node_url_str,
const Param_eth_getStorageAt *param_ptr);
//!@brief Parameter for web3_eth_getTransactionReceiptStatus()
typedef struct TParam_eth_getTransactionReceipt
{
BCHAR *tx_hash_str; //!< String of 32-byte transaction hash, e.g. "0x123456..."
}Param_eth_getTransactionReceipt;
BCHAR *web3_eth_getTransactionReceiptStatus(Web3IntfContext *web3intf_context_ptr,
BCHAR *node_url_str,
const Param_eth_getTransactionReceipt *param_ptr);
//!@brief Parameter for web3_eth_call()
typedef struct TParam_eth_call
{
BCHAR *to; //!< The address of the contract.
BCHAR *gas; //!< The gasLimit.
BCHAR *gasPrice; //!< The gasPrice in wei.
BCHAR *data; //!< The function selector followed by parameters.
BCHAR *block_num_str; //!< String of either block number or one of "latest", "earliest" and "pending"
}Param_eth_call;
BCHAR *web3_eth_call(Web3IntfContext *web3intf_context_ptr,
BCHAR *node_url_str,
const Param_eth_call *param_ptr);
typedef struct TParam_platone_call
{
BCHAR *to; //!< The address of the contract.
BCHAR *gas; //!< The gasLimit.
BCHAR *gasPrice; //!< The gasPrice in wei.
BCHAR *data; //!< The function selector followed by parameters.
BCHAR *txtype; //!< The type of contract invoked.
BCHAR *block_num_str; //!< String of either block number or one of "latest", "earliest" and "pending"
}Param_platone_call;
#ifdef __cplusplus
}
#endif /* end of __cplusplus */
#endif
|
gitter-badger/BoAT-X-Framework | tests/testmain.c | /******************************************************************************
* Copyright (C) 2018-2021 aitos.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "boatiotsdk.h"
BOAT_RESULT TestPreCondition(void);
BOAT_RESULT TestPostCondition(void);
// Case declaration
BOAT_RESULT Case_20_RlpMain(void);
BOAT_RESULT Case_10_EthFunMain(void);
BOAT_RESULT Case_11_EthCovMain(void);
BOAT_RESULT Case_15_PlatONEMain(void);
BOAT_RESULT Case_16_PlatONECovMain(void);
int main(int argc, char *argv[])
{
BOAT_RESULT case_result=BOAT_SUCCESS;
TestPreCondition();
//case_result += Case_20_RlpMain();
//case_result += Case_10_EthFunMain();
//case_result += Case_11_EthCovMain();
case_result += Case_15_PlatONEMain();
case_result += Case_16_PlatONECovMain();
BoatLog(BOAT_LOG_NORMAL, "case_result: %d.", case_result);
TestPostCondition();
return 0;
}
|
gitter-badger/BoAT-X-Framework | hwdep/default/rng/randgenerator.c | <reponame>gitter-badger/BoAT-X-Framework
/******************************************************************************
* Copyright (C) 2018-2020 aitos.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/*!@brief Default Random Number Generator
@file
randgenerate.c is the default random number generator.
*/
#include "boatinternal.h"
#if BOAT_USE_OPENSSL == 1
#include <stdio.h>
#include <openssl/rand.h>
#include "randgenerator.h"
#else
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "randgenerator.h"
#include "sha3.h"
#endif
#if BOAT_USE_OPENSSL == 1
// If OpenSSL is used, seed is automatically initialized by OpenSSL
void rand_seed_init(void)
{
return;
}
BOAT_RESULT random_stream(BUINT8 *rand_buf, BUINT16 len)
{
int rand_status;
BOAT_RESULT result = BOAT_ERROR;
rand_status = RAND_status();
if( rand_status == 1 )
{
rand_status = RAND_bytes(rand_buf, len);
if( rand_status == 1 )
{
result = BOAT_SUCCESS;
}
}
if( result == BOAT_ERROR )
{
BoatLog(BOAT_LOG_CRITICAL, "Fail to generate random number.");
}
else
{
#ifdef DEBUG_LOG
do
{
BUINT32 i;
printf("Rand: ");
for( i = 0; i < len; i++ )
{
printf("%02x", rand_buf[i]);
}
putchar('\n');
}while(0);
#endif
}
return result;
}
BUINT32 random32(void)
{
BOAT_RESULT result;
BUINT32 rand_bytes;
result = random_stream((BUINT8 *)&rand_bytes, 4);
if( result != BOAT_SUCCESS )
{
rand_bytes = 0;
}
return rand_bytes;
}
BUINT64 random64(void)
{
BOAT_RESULT result;
BUINT64 rand_bytes;
result = random_stream((BUINT8 *)&rand_bytes, 8);
if( result != BOAT_SUCCESS )
{
rand_bytes = 0;
}
return rand_bytes;
}
#else // else of #if BOAT_USE_OPENSSL == 1
BUINT8 * read_random_sdram(BUINT32 len)
{
#ifdef DEBUG_LOG
BUINT32 i;
#endif
size_t current_time;
BUINT8 *random_sdram_ptr;
BUINT8 *ret_val;
BUINT8 time_digest[32];
current_time = time(NULL);
keccak_256((unsigned char *)¤t_time, sizeof(size_t), time_digest);
// Allocate extra 256 bytes so an random offset can be given by current time
random_sdram_ptr = malloc(len+256);
if( random_sdram_ptr != NULL )
{
// Return a freed buffer increase the randomness
free(random_sdram_ptr);
// Give an offset related to current time to improve randomness
ret_val = random_sdram_ptr + time_digest[0];
}
else
{
// If malloc() fails (possibly due to out of memory), return an address
// in the stack. The content of stack is typically random.
ret_val = (BUINT8*)&ret_val + time_digest[0];
}
#ifdef DEBUG_LOG
printf("read_random_sdram() returns:\n");
for( i = 0; i < len; i++ )
{
printf("%02x", ret_val[i]);
}
putchar('\n');
#endif
return(ret_val);
}
void rand_seed_init(void)
{
size_t current_time;
BUINT8 time_digest[32];
BUINT8 sdram_digest[32];
volatile BUINT32 seed;
// Random Seed Source 1: Current Time
// NOTE: return type of time() is 64-bit or 32-bit depending on the system
current_time = time(NULL);
keccak_256((BUINT8 *)¤t_time, sizeof(size_t), time_digest);
// Random Seed Source 2: Content of random address in SDRAM
keccak_256(read_random_sdram(256),
256,
sdram_digest);
// Seed = uninitialized "seed" xor first 4 bytes of time_digest xor first 4 bytes of sdram_digest
seed ^= *(BUINT32 *)time_digest ^ *(BUINT32 *)sdram_digest;
#ifdef DEBUG_LOG
printf("rand_seed_init(): Seed is: %08x.\n", seed);
#endif
srand(seed);
return;
}
BUINT32 random32(void)
{
return ((rand() & 0xFF) | ((rand() & 0xFF) << 8) | ((rand() & 0xFF) << 16) | ((BUINT32) (rand() & 0xFF) << 24));
}
BUINT64 random64(void)
{
BUINT64 rand64;
*(BUINT32 *)&rand64 = random32();
*(((BUINT32 *)&rand64) + 1) = random32();
return (rand64);
}
BOAT_RESULT random_stream(BUINT8 *buf, BUINT16 len)
{
BUINT32 r = 0;
for (BUINT32 i = 0; i < len; i++)
{
if (i % 4 == 0)
{
r = random32();
}
buf[i] = (r >> ((i % 4) * 8)) & 0xFF;
}
return BOAT_SUCCESS;
}
#endif // else of #if BOAT_USE_OPENSSL == 1
|
gitter-badger/BoAT-X-Framework | tests/case_20_rlp.c | <filename>tests/case_20_rlp.c
/******************************************************************************
* Copyright (C) 2018-2021 aitos.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "boatinternal.h"
RlpObject g_case_rlp_object_listA;
RlpObject g_case_rlp_object_stringA1; // Test Null String
RlpObject g_case_rlp_object_stringA2;
BUINT8 g_case_rlp_object_stringA2_value[1] = {0x7F};
RlpObject g_case_rlp_object_stringA3;
BUINT8 g_case_rlp_object_stringA3_value[1] = {0x80};
RlpObject g_case_rlp_object_stringA4;
BUINT8 g_case_rlp_object_stringA4_value[2] = {0x12, 0x34};
RlpObject g_case_rlp_object_stringA5;
BUINT8 g_case_rlp_object_stringA5_value[55]; // memset to 0x11
RlpObject g_case_rlp_object_stringA6;
BUINT8 g_case_rlp_object_stringA6_value[56]; // memset to 0x22
RlpObject g_case_rlp_object_listB;
RlpObject g_case_rlp_object_stringB1;
BUINT8 g_case_rlp_object_stringB1_value[1] = {0x56};
RlpObject g_case_rlp_object_stringB2;
BUINT8 g_case_rlp_object_stringB2_value[1] = {0x78};
RlpObject g_case_rlp_object_listC; // Test Null List
void Case_20_RlpPreCondition(void)
{
memset(g_case_rlp_object_stringA5_value, 0x11, sizeof(g_case_rlp_object_stringA5_value));
memset(g_case_rlp_object_stringA6_value, 0x22, sizeof(g_case_rlp_object_stringA6_value));
}
BOAT_RESULT Case_20_RlpInitObject(void)
{
BOAT_RESULT case_result;
BOAT_RESULT call_result;
BCHAR *case_name_str;
boat_try_declare;
case_result = 0;
case_name_str = "Case_20_RlpInitObject_2010";
call_result = RlpInitListObject(&g_case_rlp_object_listA);
if( call_result == BOAT_SUCCESS )
{
BoatLog(BOAT_LOG_NORMAL, "%s Passed.", case_name_str);
}
else
{
case_result -= 1;
BoatLog(BOAT_LOG_NORMAL, "%s Failed.", case_name_str);
boat_throw(BOAT_ERROR_TEST_CASE_FAIL, Case_20_RlpInitObject_cleanup);
}
case_name_str = "Case_20_RlpInitObject_2011";
call_result = RlpInitStringObject(&g_case_rlp_object_stringA1,
NULL,
0);
if( call_result == BOAT_SUCCESS )
{
BoatLog(BOAT_LOG_NORMAL, "%s Passed.", case_name_str);
}
else
{
case_result -= 1;
BoatLog(BOAT_LOG_NORMAL, "%s Failed.", case_name_str);
boat_throw(BOAT_ERROR_TEST_CASE_FAIL, Case_20_RlpInitObject_cleanup);
}
case_name_str = "Case_20_RlpInitObject_2012";
call_result = RlpEncoderAppendObjectToList(&g_case_rlp_object_listA, &g_case_rlp_object_stringA1);
if( call_result >= BOAT_SUCCESS )
{
BoatLog(BOAT_LOG_NORMAL, "%s Passed.", case_name_str);
}
else
{
case_result -= 1;
BoatLog(BOAT_LOG_NORMAL, "%s Failed.", case_name_str);
boat_throw(BOAT_ERROR_TEST_CASE_FAIL, Case_20_RlpInitObject_cleanup);
}
case_name_str = "Case_20_RlpInitObject_2013";
call_result = RlpInitStringObject(&g_case_rlp_object_stringA2,
g_case_rlp_object_stringA2_value,
sizeof(g_case_rlp_object_stringA2_value));
if( call_result == BOAT_SUCCESS )
{
BoatLog(BOAT_LOG_NORMAL, "%s Passed.", case_name_str);
}
else
{
case_result -= 1;
BoatLog(BOAT_LOG_NORMAL, "%s Failed.", case_name_str);
boat_throw(BOAT_ERROR_TEST_CASE_FAIL, Case_20_RlpInitObject_cleanup);
}
case_name_str = "Case_20_RlpInitObject_2014";
call_result = RlpEncoderAppendObjectToList(&g_case_rlp_object_listA, &g_case_rlp_object_stringA2);
if( call_result >= BOAT_SUCCESS )
{
BoatLog(BOAT_LOG_NORMAL, "%s Passed.", case_name_str);
}
else
{
case_result -= 1;
BoatLog(BOAT_LOG_NORMAL, "%s Failed.", case_name_str);
boat_throw(BOAT_ERROR_TEST_CASE_FAIL, Case_20_RlpInitObject_cleanup);
}
case_name_str = "Case_20_RlpInitObject_2015";
call_result = RlpInitStringObject(&g_case_rlp_object_stringA3,
g_case_rlp_object_stringA3_value,
sizeof(g_case_rlp_object_stringA3_value));
if( call_result == BOAT_SUCCESS )
{
BoatLog(BOAT_LOG_NORMAL, "%s Passed.", case_name_str);
}
else
{
case_result -= 1;
BoatLog(BOAT_LOG_NORMAL, "%s Failed.", case_name_str);
boat_throw(BOAT_ERROR_TEST_CASE_FAIL, Case_20_RlpInitObject_cleanup);
}
case_name_str = "Case_20_RlpInitObject_2016";
call_result = RlpEncoderAppendObjectToList(&g_case_rlp_object_listA, &g_case_rlp_object_stringA3);
if( call_result >= BOAT_SUCCESS )
{
BoatLog(BOAT_LOG_NORMAL, "%s Passed.", case_name_str);
}
else
{
case_result -= 1;
BoatLog(BOAT_LOG_NORMAL, "%s Failed.", case_name_str);
boat_throw(BOAT_ERROR_TEST_CASE_FAIL, Case_20_RlpInitObject_cleanup);
}
case_name_str = "Case_20_RlpInitObject_2017";
call_result = RlpInitStringObject(&g_case_rlp_object_stringA4,
g_case_rlp_object_stringA4_value,
sizeof(g_case_rlp_object_stringA4_value));
if( call_result == BOAT_SUCCESS )
{
BoatLog(BOAT_LOG_NORMAL, "%s Passed.", case_name_str);
}
else
{
case_result -= 1;
BoatLog(BOAT_LOG_NORMAL, "%s Failed.", case_name_str);
boat_throw(BOAT_ERROR_TEST_CASE_FAIL, Case_20_RlpInitObject_cleanup);
}
case_name_str = "Case_20_RlpInitObject_2018";
call_result = RlpEncoderAppendObjectToList(&g_case_rlp_object_listA, &g_case_rlp_object_stringA4);
if( call_result >= BOAT_SUCCESS )
{
BoatLog(BOAT_LOG_NORMAL, "%s Passed.", case_name_str);
}
else
{
case_result -= 1;
BoatLog(BOAT_LOG_NORMAL, "%s Failed.", case_name_str);
boat_throw(BOAT_ERROR_TEST_CASE_FAIL, Case_20_RlpInitObject_cleanup);
}
case_name_str = "Case_20_RlpInitObject_2019";
call_result = RlpInitStringObject(&g_case_rlp_object_stringA5,
g_case_rlp_object_stringA5_value,
sizeof(g_case_rlp_object_stringA5_value));
if( call_result == BOAT_SUCCESS )
{
BoatLog(BOAT_LOG_NORMAL, "%s Passed.", case_name_str);
}
else
{
case_result -= 1;
BoatLog(BOAT_LOG_NORMAL, "%s Failed.", case_name_str);
boat_throw(BOAT_ERROR_TEST_CASE_FAIL, Case_20_RlpInitObject_cleanup);
}
case_name_str = "Case_20_RlpInitObject_2020";
call_result = RlpEncoderAppendObjectToList(&g_case_rlp_object_listA, &g_case_rlp_object_stringA5);
if( call_result >= BOAT_SUCCESS )
{
BoatLog(BOAT_LOG_NORMAL, "%s Passed.", case_name_str);
}
else
{
case_result -= 1;
BoatLog(BOAT_LOG_NORMAL, "%s Failed.", case_name_str);
boat_throw(BOAT_ERROR_TEST_CASE_FAIL, Case_20_RlpInitObject_cleanup);
}
case_name_str = "Case_20_RlpInitObject_2021";
call_result = RlpInitStringObject(&g_case_rlp_object_stringA6,
g_case_rlp_object_stringA6_value,
sizeof(g_case_rlp_object_stringA6_value));
if( call_result == BOAT_SUCCESS )
{
BoatLog(BOAT_LOG_NORMAL, "%s Passed.", case_name_str);
}
else
{
case_result -= 1;
BoatLog(BOAT_LOG_NORMAL, "%s Failed.", case_name_str);
boat_throw(BOAT_ERROR_TEST_CASE_FAIL, Case_20_RlpInitObject_cleanup);
}
case_name_str = "Case_20_RlpInitObject_2022";
call_result = RlpEncoderAppendObjectToList(&g_case_rlp_object_listA, &g_case_rlp_object_stringA6);
if( call_result >= BOAT_SUCCESS )
{
BoatLog(BOAT_LOG_NORMAL, "%s Passed.", case_name_str);
}
else
{
case_result -= 1;
BoatLog(BOAT_LOG_NORMAL, "%s Failed.", case_name_str);
boat_throw(BOAT_ERROR_TEST_CASE_FAIL, Case_20_RlpInitObject_cleanup);
}
case_name_str = "Case_20_RlpInitObject_2023";
call_result = RlpInitListObject(&g_case_rlp_object_listB);
if( call_result == BOAT_SUCCESS )
{
BoatLog(BOAT_LOG_NORMAL, "%s Passed.", case_name_str);
}
else
{
case_result -= 1;
BoatLog(BOAT_LOG_NORMAL, "%s Failed.", case_name_str);
boat_throw(BOAT_ERROR_TEST_CASE_FAIL, Case_20_RlpInitObject_cleanup);
}
case_name_str = "Case_20_RlpInitObject_2024";
call_result = RlpEncoderAppendObjectToList(&g_case_rlp_object_listA, &g_case_rlp_object_listB);
if( call_result >= BOAT_SUCCESS )
{
BoatLog(BOAT_LOG_NORMAL, "%s Passed.", case_name_str);
}
else
{
case_result -= 1;
BoatLog(BOAT_LOG_NORMAL, "%s Failed.", case_name_str);
boat_throw(BOAT_ERROR_TEST_CASE_FAIL, Case_20_RlpInitObject_cleanup);
}
case_name_str = "Case_20_RlpInitObject_2025";
call_result = RlpInitStringObject(&g_case_rlp_object_stringB1,
g_case_rlp_object_stringB1_value,
sizeof(g_case_rlp_object_stringB1_value));
if( call_result == BOAT_SUCCESS )
{
BoatLog(BOAT_LOG_NORMAL, "%s Passed.", case_name_str);
}
else
{
case_result -= 1;
BoatLog(BOAT_LOG_NORMAL, "%s Failed.", case_name_str);
boat_throw(BOAT_ERROR_TEST_CASE_FAIL, Case_20_RlpInitObject_cleanup);
}
case_name_str = "Case_20_RlpInitObject_2026";
call_result = RlpEncoderAppendObjectToList(&g_case_rlp_object_listB, &g_case_rlp_object_stringB1);
if( call_result >= BOAT_SUCCESS )
{
BoatLog(BOAT_LOG_NORMAL, "%s Passed.", case_name_str);
}
else
{
case_result -= 1;
BoatLog(BOAT_LOG_NORMAL, "%s Failed.", case_name_str);
boat_throw(BOAT_ERROR_TEST_CASE_FAIL, Case_20_RlpInitObject_cleanup);
}
case_name_str = "Case_20_RlpInitObject_2027";
call_result = RlpInitStringObject(&g_case_rlp_object_stringB2,
g_case_rlp_object_stringB2_value,
sizeof(g_case_rlp_object_stringB2_value));
if( call_result == BOAT_SUCCESS )
{
BoatLog(BOAT_LOG_NORMAL, "%s Passed.", case_name_str);
}
else
{
case_result -= 1;
BoatLog(BOAT_LOG_NORMAL, "%s Failed.", case_name_str);
boat_throw(BOAT_ERROR_TEST_CASE_FAIL, Case_20_RlpInitObject_cleanup);
}
case_name_str = "Case_20_RlpInitObject_2028";
call_result = RlpEncoderAppendObjectToList(&g_case_rlp_object_listB, &g_case_rlp_object_stringB2);
if( call_result >= BOAT_SUCCESS )
{
BoatLog(BOAT_LOG_NORMAL, "%s Passed.", case_name_str);
}
else
{
case_result -= 1;
BoatLog(BOAT_LOG_NORMAL, "%s Failed.", case_name_str);
boat_throw(BOAT_ERROR_TEST_CASE_FAIL, Case_20_RlpInitObject_cleanup);
}
case_name_str = "Case_20_RlpInitObject_2029";
call_result = RlpInitListObject(&g_case_rlp_object_listC);
if( call_result == BOAT_SUCCESS )
{
BoatLog(BOAT_LOG_NORMAL, "%s Passed.", case_name_str);
}
else
{
case_result -= 1;
BoatLog(BOAT_LOG_NORMAL, "%s Failed.", case_name_str);
boat_throw(BOAT_ERROR_TEST_CASE_FAIL, Case_20_RlpInitObject_cleanup);
}
case_name_str = "Case_20_RlpInitObject_2030";
call_result = RlpEncoderAppendObjectToList(&g_case_rlp_object_listB, &g_case_rlp_object_listC);
if( call_result >= BOAT_SUCCESS )
{
BoatLog(BOAT_LOG_NORMAL, "%s Passed.", case_name_str);
}
else
{
case_result -= 1;
BoatLog(BOAT_LOG_NORMAL, "%s Failed.", case_name_str);
boat_throw(BOAT_ERROR_TEST_CASE_FAIL, Case_20_RlpInitObject_cleanup);
}
boat_catch(Case_20_RlpInitObject_cleanup)
{
BoatLog(BOAT_LOG_VERBOSE, "Exception: %d", boat_exception);
}
if( case_result < 0 )
{
BoatLog(BOAT_LOG_NORMAL, "Case_20_RlpInitObject Failed: %d.", case_result);
return case_result;
}
else
{
BoatLog(BOAT_LOG_NORMAL, "Case_20_RlpInitObject Passed.");
return BOAT_SUCCESS;
}
}
BOAT_RESULT Case_20_RlpEncode(void)
{
RlpEncodedStreamObject parent_storage;
BUINT8 parent_storage_buffer[8];
BOAT_RESULT call_result;
BOAT_RESULT case_result;
BCHAR *case_name_str;
BUINT32 i;
boat_try_declare;
memset(parent_storage_buffer, 0x00, sizeof(parent_storage_buffer));
case_result = 0;
case_name_str = "Case_20_RlpEncode_2110";
call_result = RlpEncode(&g_case_rlp_object_stringA4, NULL);
if( call_result != BOAT_SUCCESS )
{
BoatLog(BOAT_LOG_NORMAL, "%s Passed.", case_name_str);
}
else
{
case_result -= 1;
BoatLog(BOAT_LOG_NORMAL, "%s Failed.", case_name_str);
boat_throw(BOAT_ERROR_TEST_CASE_FAIL, Case_20_RlpEncode_cleanup);
}
case_name_str = "Case_20_RlpEncode_2111";
parent_storage.stream_ptr = parent_storage_buffer;
parent_storage.stream_len = 1;
call_result = RlpEncode(&g_case_rlp_object_stringA4, &parent_storage);
if( call_result != BOAT_SUCCESS )
{
BoatLog(BOAT_LOG_NORMAL, "%s Passed.", case_name_str);
}
else
{
case_result -= 1;
BoatLog(BOAT_LOG_NORMAL, "%s Failed.", case_name_str);
boat_throw(BOAT_ERROR_TEST_CASE_FAIL, Case_20_RlpEncode_cleanup);
}
case_name_str = "Case_20_RlpEncode_2112";
parent_storage.stream_ptr = parent_storage_buffer;
parent_storage.stream_len = 3;
call_result = RlpEncode(&g_case_rlp_object_stringA4, &parent_storage);
if( call_result == BOAT_SUCCESS )
{
BoatLog(BOAT_LOG_NORMAL, "%s: parent_storage.stream_len = %u.", case_name_str, parent_storage.stream_len);
for( i = 0; i < parent_storage.stream_len; i++ )
{
printf("%02x ", parent_storage.stream_ptr[i]);
}
putchar('\n');
BoatLog(BOAT_LOG_NORMAL, "%s Passed.", case_name_str);
}
else
{
case_result -= 1;
BoatLog(BOAT_LOG_NORMAL, "%s Failed.", case_name_str);
boat_throw(BOAT_ERROR_TEST_CASE_FAIL, Case_20_RlpEncode_cleanup);
}
case_name_str = "Case_20_RlpEncode_2113";
call_result = RlpEncode(&g_case_rlp_object_listA, NULL);
if( call_result == BOAT_SUCCESS )
{
RlpEncodedStreamObject *storage_ptr;
storage_ptr = RlpGetEncodedStream(&g_case_rlp_object_listA);
BoatLog(BOAT_LOG_NORMAL, "%s: Encoded RLP stream: %u bytes.", case_name_str, storage_ptr->stream_len);
for( i = 0; i < storage_ptr->stream_len; i++ )
{
printf("%02x ", g_case_rlp_object_listA.object_list.rlp_encoded_stream_object.stream_ptr[i]);
}
putchar('\n');
BoatLog(BOAT_LOG_NORMAL, "%s Passed.", case_name_str);
}
else
{
case_result -= 1;
BoatLog(BOAT_LOG_NORMAL, "%s Failed.", case_name_str);
boat_throw(BOAT_ERROR_TEST_CASE_FAIL, Case_20_RlpEncode_cleanup);
}
boat_catch(Case_20_RlpEncode_cleanup)
{
BoatLog(BOAT_LOG_VERBOSE, "Exception: %d", boat_exception);
}
if( case_result < 0 )
{
BoatLog(BOAT_LOG_NORMAL, "Case_20_RlpEncode Failed: %d.", case_result);
return case_result;
}
else
{
BoatLog(BOAT_LOG_NORMAL, "Case_20_RlpEncode Passed.");
return BOAT_SUCCESS;
}
}
BOAT_RESULT Case_20_RlpDelete(void)
{
RlpRecursiveDeleteObject(&g_case_rlp_object_listA);
return BOAT_SUCCESS;
}
BOAT_RESULT Case_20_RlpMain(void)
{
BOAT_RESULT case_result = BOAT_SUCCESS;
Case_20_RlpPreCondition();
case_result += Case_20_RlpInitObject();
case_result += Case_20_RlpEncode();
case_result += Case_20_RlpDelete();
if( case_result != BOAT_SUCCESS )
{
BoatLog(BOAT_LOG_NORMAL, "Case_20_Rlp Failed: %d.", case_result);
}
else
{
BoatLog(BOAT_LOG_NORMAL, "Case_20_Rlp Passed.");
}
return case_result;
}
|
gitter-badger/BoAT-X-Framework | include/boatoptions.h | <gh_stars>1-10
/******************************************************************************
* Copyright (C) 2018-2021 aitos.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/*!@brief Boatwallet options
@file
boatoptions.h defines options for compiling.
*/
#ifndef __BOATOPTIONS_H__
#define __BOATOPTIONS_H__
// BOAT LOG LEVEL DEFINITION
// Log level is used to control the detail of log output.
// 3 types of detail level can be specified in BoatLog():
// "CRITICAL" is for critical exceptions that may halt the wallet from going on.
// "NORMAL" is for warnings that may imply some error but could be held.
// "VERBOSE" is for detail information that is only useful for debug.
#define BOAT_LOG_NONE 0
#define BOAT_LOG_CRITICAL 1
#define BOAT_LOG_NORMAL 2
#define BOAT_LOG_VERBOSE 3
// BOAT_LOG_LEVEL is a macro that limits the log detail up to that level.
// Seting it to BOAT_LOG_NONE means outputing nothing.
#define BOAT_LOG_LEVEL BOAT_LOG_VERBOSE
// #define DEBUG_LOG
// OpenSSL OPTION: Use OpenSSL for random number generation and AES
#define BOAT_USE_OPENSSL 1
// RPC USE OPTION: One and only one RPC_USE option shall be set to 1
#define RPC_USE_LIBCURL 1
#define RPC_USE_NOTHING 0
#define RPC_USE_COUNT ( \
RPC_USE_LIBCURL + \
RPC_USE_NOTHING)
#if RPC_USE_COUNT != 1
#error "One and only one RPC_USE option shall be set to 1"
#endif
#undef RPC_USE_COUNT
// Blockchain Protocol OPTION
#define PROTOCOL_USE_ETHEREUM 1
#define PROTOCOL_USE_HLFABRIC 0
#define PROTOCOL_USE_PLATONE 1
// Protocol dependency
#if PROTOCOL_USE_PLATONE != 0
#undef PROTOCOL_USE_ETHEREUM
#define PROTOCOL_USE_ETHEREUM 1
#endif
#define PROTOCOL_USE_COUNT (\
PROTOCOL_USE_ETHEREUM + \
PROTOCOL_USE_HLFABRIC + \
PROTOCOL_USE_PLATONE )
#if PROTOCOL_USE_COUNT == 0
#error "At least ONE PROTOCOL_USE option shall be set to 1"
#endif
#undef PROTOCOL_USE_COUNT
// Mining interval and Pending transaction timeout
#define BOAT_MINE_INTERVAL 3 // Mining Interval of the blockchain, in seconds
#define BOAT_WAIT_PENDING_TX_TIMEOUT 30 // Timeout waiting for a transaction being mined, in seconds
// Maxmum length for node's URL
#define BOAT_NODE_URL_MAX_LEN 127
#endif
|
gitter-badger/BoAT-X-Framework | include/boatwallet.h | <gh_stars>1-10
/******************************************************************************
* Copyright (C) 2018-2021 aitos.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/*!@brief Boatwallet SDK header file
@file
boatwallet.h is the SDK header file.
*/
#ifndef __BOATWALLET_H__
#define __BOATWALLET_H__
#include "boatiotsdk.h"
typedef union TBoatWalletInfo
{
#if PROTOCOL_USE_ETHEREUM == 1
BoatEthWallet *boat_eth_wallet_info_ptr;
#endif
#if PROTOCOL_USE_HLFABRIC == 1
BoatHLFabricWallet *boat_hlfabric_wallet_info_ptr;
#endif
#if PROTOCOL_USE_PLATONE == 1
BoatPlatoneWallet *boat_platone_wallet_info_ptr;
#endif
}BoatWalletInfo;
typedef struct TBoatWalletList
{
BBOOL is_used;
BoatProtocolType protocol_type; //!< Blockchain protocol type
BCHAR *wallet_name_str; //!< Wallet name for persist wallet, NULL for one-time wallet
void * wallet_ptr; //!< Wallet context of one of BoatWalletInfo type
}BoatWalletList;
#define BOAT_MAX_WALLET_NUM 4
//!@brief BoAT IoT SDK Context
typedef struct TBoatIotSdkContext
{
// Protocol specifiec properties are defined in protocol specific WalletInfo structure
BoatWalletList wallet_list[BOAT_MAX_WALLET_NUM]; //!< Wallet Info List
}BoatIotSdkContext;
#ifdef __cplusplus
extern "C" {
#endif
/*!*****************************************************************************
@brief Initialize Boat IoT SDK
Function: BoatIotSdkInit()
This function initialize global context of Boat IoT SDK.
BoatIotSdkInit() MUST be called before any use of BoAT IoT SDK per process.
BoatIotSdkDeInit() MUST be called after use of BoAT IoT SDK.
@see BoatIotSdkDeInit()
@return
This function returns BOAT_SUCCESS if initialization is successful.\n
Otherwise it returns BOAT_ERROR.
@param This function doesn't take any argument.
*******************************************************************************/
BOAT_RESULT BoatIotSdkInit(void);
/*!*****************************************************************************
@brief De-initialize BoAT IoT SDK
Function: BoatIotSdkDeInit()
This function de-initialize context of BoAT IoT SDK.
BoatIotSdkInit() MUST be called before any use of BoAT IoT SDK per process.
BoatIotSdkDeInit() MUST be called after use of BoAT IoT SDK.
@see BoatIotSdkInit()
@return This function doesn't return any thing.
*******************************************************************************/
void BoatIotSdkDeInit(void);
/*!*****************************************************************************
@brief Create BoAT wallet
Function: BoatWalletCreate()
This function creates a wallet or loads an existed persistent wallet.
A wallet is a configuration for blockchain parameters as well as context for
blockchain operations. There are 2 types of wallet. One is a one-time wallet,
which only exists in RAM and disappears once the device is powered down. The
other is a persistent wallet, which is saved in non-volatile memory for later
loading.
If the given <wallet_name_str> is NULL, a one-time wallet is created. Otherwise
a persistent wallet with the given name will be created or loaded. If no wallet
with the given name exists, a new persistent wallet will be created with the
name and immediately loaded into RAM. If a persistent wallet with the given
name exists, it will be loaded into RAM.
To create a one-time wallet, <wallet_name_str> MUST be NULL and a non-NULL
<wallet_config_ptr> MUST be specified.
To create a persistent wallet, <wallet_name_str>, <wallet_config_ptr> and
<wallet_config_size> MUST be specified. If a persitent wallet with the given
<wallet_name_str> exists, the specified configuration will overwrite the
existed one, both in RAM and in non-volatile memroy.
To load an existed persistent wallet into RAM, specify its name in <wallet_name_str>,
specify <wallet_config_ptr> = NULL and <wallet_config_size> = the configuration
size of the specified <protocol_type>.
To unload a wallet from RAM, which was loaded by BoatWalletCreate(), call
BoatWalletUnload(). For persisent wallet, this does NOT delete it from
non-volatile memory.
To delete a persistent wallet from non-volatile memroy, call BoatWalletDelete().
This does NOT unload it from RAM. If a loaded persistent wallet is deleted
without unloading it, it becomes a one-time wallet.
@see BoatWalletUnload() BoatWalletDelete()
@return
This function returns the non-negative index of the loaded wallet.\n
It returns -1 if wallet creation fails.
@param[in] protocol_type
The blockchain protocol. See boattypes.h for supported protocol.
@param[in] wallet_name_str
A string of wallet name.\n
If the given <wallet_name_str> is NULL, a one-time wallet is created.\n
Otherwise a persistent wallet with the given name will be created or loaded.
@param[in] wallet_config_ptr
Configuration (e.g. crypto key) for the wallet.\n
The exact configuration definition is determinted by the specified <protocol_type>.
@param[in] wallet_config_size
Size (in byte) of configuration specified by <wallet_config_ptr>.
*******************************************************************************/
BSINT32 BoatWalletCreate(BoatProtocolType protocol_type, const BCHAR *wallet_name_str, const void * wallet_config_ptr, BUINT32 wallet_config_size);
/*!*****************************************************************************
@brief Unload a wallet
Function: BoatWalletUnload()
This function unloads a wallet from RAM if no more operations on this wallet
is required. If the wallet is of persistent type, this function will NOT
delete it from non-volatile memory. To delete a persistent wallet from
non-volatile memory, call BoatWalletDelete().
@see BoatWalletCreate() BoatWalletDelete()
@return This function doesn't return any thing.
@param[in] wallet_index
The wallet index to unload.
*******************************************************************************/
void BoatWalletUnload(BSINT32 wallet_index);
/*!*****************************************************************************
@brief Delete a persistent wallet
Function: BoatWalletDelete()
This function deletes a persistent wallet from non-volatile memory. This
does NOT unload it from RAM. If a loaded persistent wallet is deleted
without unloading it, it becomes a one-time wallet.
@see BoatWalletCreate() BoatWalletUnload()
@return This function doesn't return any thing.
@param[in] wallet_name_str
The wallet name to delete.
*******************************************************************************/
void BoatWalletDelete(BCHAR * wallet_name_str);
/*!*****************************************************************************
@brief Get the BoAT wallet context by index.
Function: BoatGetWalletByIndex()
This function gets the BoAT wallet context by index.
@return This function returns a pointer to the wallet context.
@param[in] wallet_index
The wallet index.
*******************************************************************************/
void * BoatGetWalletByIndex(BSINT32 wallet_index);
#ifdef __cplusplus
}
#endif /* end of __cplusplus */
#endif
|
gitter-badger/BoAT-X-Framework | sdk/rpc/rpcintf.h | /******************************************************************************
* Copyright (C) 2018-2020 aitos.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/*!@brief RPC wrapper header file
@file
rpcintf.h is header file for RPC wrapper functions.
The exact implementation of the actual RPC mechanism is controlled by
RPC_USE_XXX macros.
*/
#ifndef __RPCINTF_H__
#define __RPCINTF_H__
#include "boatinternal.h"
#if RPC_USE_LIBCURL == 1
#include "curl/curl.h"
#endif
#ifdef __cplusplus
extern "C" {
#endif
void* RpcInit(void);
void RpcDeinit(void *rpc_context_ptr);
BOAT_RESULT RpcRequestSync(void *rpc_context_ptr,
BUINT8 *request_ptr,
BUINT32 request_len,
BOAT_OUT BUINT8 **response_pptr,
BOAT_OUT BUINT32 *response_len_ptr);
#ifdef __cplusplus
}
#endif /* end of __cplusplus */
#endif
|
gitter-badger/BoAT-X-Framework | include/protocolapi/api_platone.h | <reponame>gitter-badger/BoAT-X-Framework
/******************************************************************************
* Copyright (C) 2018-2021 aitos.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/*!@brief BoAT IoT SDK interface header file for PlatONE
@file
api_platone.h is header file for BoAT IoT SDK PlatONE's interface.
*/
#ifndef __API_PLATONE_H__
#define __API_PLATONE_H__
#include "boatiotsdk.h"
#if PROTOCOL_USE_PLATONE == 1
#include "api_ethereum.h"
#define BOAT_PLATONE_ADDRESS_SIZE BOAT_ETH_ADDRESS_SIZE
typedef enum
{
BOAT_PLATONE_TX_TYPE_NORMAL_TRANSFER = 0x00,
BOAT_PLATONE_TX_TYPE_CONTRACT = 0x02,
BOAT_PLATONE_TX_TYPE_CONTRACT_NULL_TERMED_STR = 0x09,
}BoatPlatoneTxtype;
typedef BoatEthAccountInfo BoatPlatoneAccountInfo;
typedef BoatEthNetworkInfo BoatPlatoneNetworkInfo;
typedef BoatEthWallet BoatPlatoneWallet;
typedef BoatEthWalletConfig BoatPlatoneWalletConfig;
typedef BoatEthTxFieldSig BoatPlatoneTxFieldSig;
//!@brief RAW PlatONE transaction fields
//! The only difference from Ethereum is appending a txtype field at the end of the
//! struct. Thus a BoatPlatoneRawtxFields pointer can be transfered to any function
//! that accepts a BoatEthRawtxFields argument. It behaves as a C implementation of
//! class inheritance, i.e. a pointer of an inherited class could be assigned to a
//! pointer of a base class.
typedef struct TBoatPlatoneRawtxFields
{
// Following fields are inherited from Ethereum.
// DO NOT modify these fields unless all of Ethereum and all other protocols
// inherited from Ethereum are modified synchronously.
BoatFieldMax32B nonce; //!< nonce, uint256 in bigendian, equal to the transaction count of the sender's account address
BoatFieldMax32B gasprice; //!< gasprice in wei, uint256 in bigendian
BoatFieldMax32B gaslimit; //!< gaslimit, uint256 in bigendian
BUINT8 recipient[BOAT_ETH_ADDRESS_SIZE]; //!< recipient's address, 160 bits
BoatFieldMax32B value; //!< value to transfer, uint256 in bigendian
BoatFieldVariable data; //!< data to transfer, unformatted stream
BoatFieldMax4B v; //!< chain id or recovery identifier, @see RawtxPerform()
BoatEthTxFieldSig sig; //!< ECDSA signature, including r and s parts
// PlatONE specific fields are appended here.
BoatPlatoneTxtype txtype; //!< Transaction Type
}BoatPlatoneRawtxFields;
//!@brief PlatONE Transaction
//! The only difference between PlatONE transaction and Ethereum transaction is
//! BoatPlatoneRawtxFields has more fields than BoatEthRawtxFields. To allow
//! PlatONE to re-use Ethereum APIs that take BoatEthTx as function arguments,
//! <rawtx_fields> MUST be the last field.
typedef struct TBoatPlatoneTx
{
BoatPlatoneWallet *wallet_ptr; //!< Wallet pointer the transaction is combined with
BoatFieldMax32B tx_hash; //!< Transaction hash returned from network
BBOOL is_sync_tx; //!< True to perform a synchronous transaction (wait for getting mined), False for asynchronous transaction
// rawtx_fields MUST be the last field
BoatPlatoneRawtxFields rawtx_fields; //!< RAW transaction fields
}BoatPlatoneTx;
#ifdef __cplusplus
extern "C" {
#endif
/*!*****************************************************************************
@brief Sign and send a transaction. Also call a stateful contract function.
Function: BoatPlatoneTxSend()
This function sign and set a transaction.
BoatWalletSetXXX() and BoatTxSetXXX() functions must be properly called
before call this function.
A transaction whose recipient may be an EOA address or a contract address.
In latter case it's usually a contract function call.
This function invokes the eth_sendRawTransaction RPC method.
eth_sendRawTransaction method only applies the transaction and returns a
transaction hash. The transaction is not verified (got mined) until the
nodes in the network get into consensus about the transaction. This
function will invoke eth_getTransactionReceipt method to wait for the
transaction being mined or timeout.
If the transaction is a contract function call, the caller cannot get its
return value because the transaction is asynchronously executed. It's a
good practice to save the return value in a state variable and use
BoatPlatoneCallContractFunc() to call a "read" contract function that could read
and return the state variable.
NOTE:
Any contract function that may change the state of the contract shall
be called in a transaction way. "state" is the "global variable" used in a
contract.
Any contract function that doesn't change the state of the contract can
be called either in a transaction way or by BoatPlatoneCallContractFunc(), which
invokes the eth_call RPC method. However the former will consume gas and
latter doesn't consume gas.
@return
This function returns BOAT_SUCCESS if setting is successful.\n
Otherwise it returns one of the error codes.
@param[in] tx_ptr
Pointer to the transaction structure.
*******************************************************************************/
BOAT_RESULT BoatPlatoneTxSend(BoatPlatoneTx *tx_ptr);
/******************************************************************************
@brief Initialize PlatONE Transaction
Function: BoatPlatoneTxInit()
This function initialize an PlatONE transaction.
@see BoatEthTxInit() BoatPlatoneTxSetTxtype()
@return
This function returns BOAT_SUCCESS if initialization is successful.\n
Otherwise it returns BOAT_ERROR.
@param[in] wallet_ptr
The wallet pointer that this transaction is combined with.
@param[in] tx_ptr
Pointer a transaction object.
@param[in] is_sync_tx
For a stateful transaction, specify BOAT_TRUE to wait until the transaction is mined.\n
Specifiy BOAT_FALSE to allow multiple transactions to be sent continuously in a short time.\n
For a state-less contract call, this option is ignored.
@param[in] gasprice_str
A HEX string representing the gas price (unit: wei) to be used in the transaction.\n
Set <gasprice> = NULL to obtain gas price from network.\n
BoatPlatoneTxSetGasPrice() can later be called to modify the gas price at any\n
time before the transaction is executed.
@param[in] gaslimit_str
A HEX string representing the gas limit to be used in the transaction.\n
BoatPlatoneTxSetGasLimit() can later be called to modify the gas limit at any\n
time before the transaction is executed.
@param[in] recipient_str
A HEX string representing the recipient address, in HEX format like\n
"0x19c91A4649654265823512a457D2c16981bB64F5".\n
BoatPlatoneTxSetRecipient() can later be called to modify the recipient at any\n
time before the transaction is executed.
@param[in] txtype
Transaction type defined by BoatPlatoneTxtype.
*******************************************************************************/
BOAT_RESULT BoatPlatoneTxInit(BoatPlatoneWallet *wallet_ptr,
BoatPlatoneTx *tx_ptr,
BBOOL is_sync_tx,
BCHAR * gasprice_str,
BCHAR * gaslimit_str,
BCHAR *recipient_str,
BoatPlatoneTxtype txtype);
/*!*****************************************************************************
@brief Transfer PlatONE value to spceified recipient
Function: BoatPlatoneTransfer()
This function transfer PlatONE value from the wallet's owner account to the
specified recipient account.
Before calling this function, all necessary wallet fields such as private key,
node URL and etc. must be set correctly.
@return
This function returns BOAT_SUCCESS if transfer is successful.\n
Otherwise it returns one of the error codes.
@param[in] tx_ptr
Transaction pointer.
@param[in] value_hex_str
A string representing the value (Unit: wei) to transfer, in HEX format like\n
"0x89AB3C".\n
Note that decimal value is not accepted. If a decimal value such as "1234"\n
is specified, it's treated as "0x1234".
*******************************************************************************/
BOAT_RESULT BoatPlatoneTransfer(BoatPlatoneTx *tx_ptr, BCHAR * value_hex_str);
/******************************************************************************
@brief Set Platon Transaction Parameter: Transaction Type
Function: BoatPlatoneTxSetTxtype()
This function sets the type of transaction
@return
This function returns BOAT_SUCCESS if setting is successful.\n
Otherwise it returns one of the error codes.
@param[in] tx_ptr
The nonce obtained from network is set in BoatPlatoneTx structure.
@param[in] txtype
The transaction type.
*******************************************************************************/
BOAT_RESULT BoatPlatoneTxSetTxtype(BoatPlatoneTx *tx_ptr, BoatPlatoneTxtype txtype);
/******************************************************************************
@brief Call a state-less contract function
Function: BoatPlatoneCallContractFunc()
This function calls contract function that doesn't change the state of the
contract. "state" is the "global variable" used in a contract.
This function invokes the eth_call RPC method. eth_call method requests the
blockchain node to execute the function without affecting the block chain.
The execution runs only on the requested node thus it can return immediately
after the execution. This function synchronously return the return value
of the eth_call method, which is the return value of the contract function.
To call contract function that may change the state, use BoatPlatoneTxSend()
instead.
If call a contract function that may change the state with
BoatPlatoneCallContractFunc(), the function will be executed and return a value,
but none of the states will change.
@see BoatPlatoneTxSend()
@return
This function returns a HEX string representing the return value of the\n
called contract function.\n
If any error occurs, it returns NULL.
@param[in] tx_ptr
Transaction pointer
@param[in] rlp_param_ptr
A byte stream containing the parameters to pass to the function.\n
The stream is encoded in RLP format including the function name followed by\n
all parameters.
@param[in] rlp_param_len
Length of <rlp_param_ptr> in byte.
*******************************************************************************/
BCHAR * BoatPlatoneCallContractFunc(BoatPlatoneTx *tx_ptr, BUINT8 *rlp_param_ptr, BUINT32 rlp_param_len);
// Ethereum APIs compatible for PlatONE
//!@brief Initialize Boat PlatONE Wallet
//!@see BoatEthWalletInit()
__BOATSTATIC __BOATINLINE BoatPlatoneWallet * BoatPlatoneWalletInit(const BoatPlatoneWalletConfig *config_ptr, BUINT32 config_size)
{
return BoatEthWalletInit((const BoatEthWalletConfig *) config_ptr, config_size);
}
//!@brief De-initialize Boat PlatONE Wallet
//!@see BoatEthWalletDeInit
__BOATSTATIC __BOATINLINE void BoatPlatoneWalletDeInit(BoatPlatoneWallet *wallet_ptr)
{
return BoatEthWalletDeInit((BoatEthWallet *) wallet_ptr);
}
//!@brief Set Node Url
//!@see BoatEthWalletSetNodeUrl()
__BOATSTATIC __BOATINLINE BOAT_RESULT BoatPlatoneWalletSetNodeUrl(BoatPlatoneWallet *wallet_ptr, const BCHAR *node_url_ptr)
{
return BoatEthWalletSetNodeUrl((BoatEthWallet *)wallet_ptr, node_url_ptr);
}
//!@brief Set EIP155
//!@see BoatEthWalletSetEIP155Comp()
__BOATSTATIC __BOATINLINE BOAT_RESULT BoatPlatoneWalletSetEIP155Comp(BoatPlatoneWallet *wallet_ptr, BUINT8 eip155_compatibility)
{
return BoatEthWalletSetEIP155Comp((BoatEthWallet *)wallet_ptr,eip155_compatibility);
}
//!@brief Set ChainId
//!@see BoatEthWalletSetChainId()
__BOATSTATIC __BOATINLINE BOAT_RESULT BoatPlatoneWalletSetChainId(BoatPlatoneWallet *wallet_ptr, BUINT32 chain_id)
{
return BoatEthWalletSetChainId((BoatEthWallet *)wallet_ptr,chain_id);
}
//!@brief Set Privkey
//!@see BoatEthWalletSetPrivkey()
__BOATSTATIC __BOATINLINE BOAT_RESULT BoatPlatoneWalletSetPrivkey(BoatPlatoneWallet *wallet_ptr, const BUINT8 priv_key_array[32])
{
return BoatEthWalletSetPrivkey((BoatEthWallet *)wallet_ptr,priv_key_array);
}
//!@brief Generate Privkey
//!@see BoatEthWalletGeneratePrivkey()
__BOATSTATIC __BOATINLINE BOAT_RESULT BoatPlatoneWalletGeneratePrivkey(BOAT_OUT BUINT8 priv_key_array[32])
{
return BoatEthWalletGeneratePrivkey(priv_key_array);
}
//!@brief Check Privkey
//!@see BoatEthWalletCheckPrivkey()
__BOATSTATIC __BOATINLINE BOAT_RESULT BoatPlatoneWalletCheckPrivkey(const BUINT8 priv_key_array[32])
{
return BoatEthWalletCheckPrivkey(priv_key_array);
}
//!@brief Get Balance
//!@see BoatEthWalletGetBalance()
__BOATSTATIC __BOATINLINE BCHAR * BoatPlatoneWalletGetBalance(BoatPlatoneWallet *wallet_ptr, BCHAR *alt_address_str)
{
return BoatEthWalletGetBalance((BoatEthWallet *)wallet_ptr, alt_address_str);
}
#define BOAT_PLATONE_NONCE_AUTO BOAT_ETH_NONCE_AUTO
//!@brief Set Nonce
//!@see BoatEthTxSetNonce()
__BOATSTATIC __BOATINLINE BOAT_RESULT BoatPlatoneTxSetNonce(BoatPlatoneTx *tx_ptr, BUINT64 nonce)
{
return BoatEthTxSetNonce((BoatEthTx *)tx_ptr, nonce);
}
//!@brief Set GasPrice
//!@see BoatEthTxSetGasPrice()
__BOATSTATIC __BOATINLINE BOAT_RESULT BoatPlatoneTxSetGasPrice(BoatPlatoneTx *tx_ptr, BoatFieldMax32B *gas_price_ptr)
{
return BoatEthTxSetGasPrice((BoatEthTx *)tx_ptr, gas_price_ptr);
}
//!@brief Set GasLimit
//!@see BoatEthTxSetGasLimit()
__BOATSTATIC __BOATINLINE BOAT_RESULT BoatPlatoneTxSetGasLimit(BoatPlatoneTx *tx_ptr, BoatFieldMax32B *gas_limit_ptr)
{
return BoatEthTxSetGasLimit((BoatEthTx *)tx_ptr, gas_limit_ptr);
}
//!@brief Set Recipient
//!@see BoatEthTxSetRecipient()
__BOATSTATIC __BOATINLINE BOAT_RESULT BoatPlatoneTxSetRecipient(BoatPlatoneTx *tx_ptr, BUINT8 address[BOAT_PLATONE_ADDRESS_SIZE])
{
return BoatEthTxSetRecipient((BoatEthTx *)tx_ptr,address);
}
//!@brief Set Value
//!@see BoatEthTxSetValue()
__BOATSTATIC __BOATINLINE BOAT_RESULT BoatPlatoneTxSetValue(BoatPlatoneTx *tx_ptr, BoatFieldMax32B *value_ptr)
{
return BoatEthTxSetValue((BoatEthTx *)tx_ptr,value_ptr);
}
//!@brief Set Data
//!@see BoatEthTxSetData()
__BOATSTATIC __BOATINLINE BOAT_RESULT BoatPlatoneTxSetData(BoatPlatoneTx *tx_ptr, BoatFieldVariable *data_ptr)
{
return BoatEthTxSetData((BoatEthTx *)tx_ptr,data_ptr);
}
//!@brief Wait for a transaction being mined.
//!@see BoatEthGetTransactionReceipt
__BOATSTATIC __BOATINLINE BOAT_RESULT BoatPlatoneGetTransactionReceipt(BoatPlatoneTx *tx_ptr)
{
return BoatEthGetTransactionReceipt((BoatEthTx *) tx_ptr);
}
#ifdef __cplusplus
}
#endif /* end of __cplusplus */
#endif /* end of PROTOCOL_USE_PLATONE */
#endif
|
gitter-badger/BoAT-X-Framework | sdk/wallet/api_platone.c | <filename>sdk/wallet/api_platone.c
/******************************************************************************
* Copyright (C) 2018-2021 aitos.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/*!@brief Platone wallet API for BoAT IoT SDK
@file
boatPlatonewallet.c defines the Platone wallet API for BoAT IoT SDK.
*/
#include "boatinternal.h"
#if PROTOCOL_USE_PLATONE == 1
#include "web3intf.h"
#include "boatprotocols.h"
#include "rpcintf.h"
#include "randgenerator.h"
#include "bignum.h"
#include "cJSON.h"
#if BOAT_USE_OPENSSL != 0
#include <openssl/evp.h>
#include <openssl/aes.h>
#endif
// As Platone's wallet structure is mostly the same as Ethereum and PlatON, thus it
// re-use a lot of Ethereum and PlatON's data structure and API.
// APIs not listed here are compatible with Ethereum/PlatON.
/******************************************************************************
@brief Set Platone Transaction Parameter: Transaction Type
Function: BoatPlatoneTxSetTxtype()
This function sets the type of transaction
@return
This function returns BOAT_SUCCESS if setting is successful.\n
Otherwise it returns one of the error codes.
@param[in] tx_ptr
The nonce obtained from network is set in BoatPlatoneTx structure.
@param[in] txtype
The transaction type.
*******************************************************************************/
BOAT_RESULT BoatPlatoneTxSetTxtype(BoatPlatoneTx *tx_ptr, BoatPlatoneTxtype txtype)
{
if( tx_ptr == NULL )
{
BoatLog(BOAT_LOG_NORMAL, "Argument cannot be NULL.");
return BOAT_ERROR_INVALID_ARGUMENT;
}
tx_ptr->rawtx_fields.txtype = txtype;
return BOAT_SUCCESS;
}
/******************************************************************************
@brief Sign and send a transaction. Also call a stateful contract function.
Function: BoatPlatoneTxSend()
This function sign and set a transaction.
BoatWalletSetXXX() and BoatTxSetXXX() functions must be properly called
before call this function.
A transaction whose recipient may be an EOA address or a contract address.
In latter case it's usually a contract function call.
This function invokes the eth_sendRawTransaction RPC method.
eth_sendRawTransaction method only applies the transaction and returns a
transaction hash. The transaction is not verified (got mined) until the
nodes in the network get into consensus about the transaction. This
function will invoke eth_getTransactionReceipt method to wait for the
transaction being mined or timeout.
If the transaction is a contract function call, the caller cannot get its
return value because the transaction is asynchronously executed. It's a
good practice to save the return value in a state variable and use
BoatPlatoneCallContractFunc() to call a "read" contract function that could read
and return the state variable.
NOTE:
Any contract function that may change the state of the contract shall
be called in a transaction way. "state" is the "global variable" used in a
contract.
Any contract function that doesn't change the state of the contract can
be called either in a transaction way or by BoatPlatoneCallContractFunc(), which
invokes the eth_call RPC method. However the former will consume gas and
latter doesn't consume gas.
@see BoatPlatonTxSend()
@return
This function returns BOAT_SUCCESS if setting is successful.\n
Otherwise it returns one of the error codes.
@param[in] tx_ptr
Pointer to the transaction structure.
*******************************************************************************/
BOAT_RESULT BoatPlatoneTxSend(BoatPlatoneTx *tx_ptr)
{
BOAT_RESULT result;
if( tx_ptr == NULL || tx_ptr->wallet_ptr == NULL )
{
BoatLog(BOAT_LOG_NORMAL, "Arguments cannot be NULL.");
return BOAT_ERROR_INVALID_ARGUMENT;
}
if( tx_ptr->is_sync_tx == BOAT_FALSE )
{
result = PlatoneSendRawtx(tx_ptr);
}
else
{
result = PlatoneSendRawtxWithReceipt(tx_ptr);
}
return result;
}
/******************************************************************************
@brief Initialize PlatONE Transaction
Function: BoatPlatoneTxInit()
This function initialize an PlatONE transaction.
@see BoatEthTxInit() BoatPlatoneTxSetTxtype()
@return
This function returns BOAT_SUCCESS if initialization is successful.\n
Otherwise it returns BOAT_ERROR.
@param[in] wallet_ptr
The wallet pointer that this transaction is combined with.
@param[in] tx_ptr
Pointer a transaction object.
@param[in] is_sync_tx
For a stateful transaction, specify BOAT_TRUE to wait until the transaction is mined.\n
Specifiy BOAT_FALSE to allow multiple transactions to be sent continuously in a short time.\n
For a state-less contract call, this option is ignored.
@param[in] gasprice_str
A HEX string representing the gas price (unit: wei) to be used in the transaction.\n
Set <gasprice> = NULL to obtain gas price from network.\n
BoatPlatoneTxSetGasPrice() can later be called to modify the gas price at any\n
time before the transaction is executed.
@param[in] gaslimit_str
A HEX string representing the gas limit to be used in the transaction.\n
BoatPlatoneTxSetGasLimit() can later be called to modify the gas limit at any\n
time before the transaction is executed.
@param[in] recipient_str
A HEX string representing the recipient address, in HEX format like\n
"0x19c91A4649654265823512a457D2c16981bB64F5".\n
BoatPlatoneTxSetRecipient() can later be called to modify the recipient at any\n
time before the transaction is executed.
@param[in] txtype
Transaction type defined by BoatPlatoneTxtype.
*******************************************************************************/
BOAT_RESULT BoatPlatoneTxInit(BoatPlatoneWallet *wallet_ptr,
BoatPlatoneTx *tx_ptr,
BBOOL is_sync_tx,
BCHAR * gasprice_str,
BCHAR * gaslimit_str,
BCHAR *recipient_str,
BoatPlatoneTxtype txtype)
{
BOAT_RESULT result;
if( wallet_ptr == NULL || tx_ptr == NULL || recipient_str == NULL)
{
BoatLog(BOAT_LOG_NORMAL, "Argument cannot be NULL.");
return BOAT_ERROR_INVALID_ARGUMENT;
}
tx_ptr->wallet_ptr = wallet_ptr;
memset(&tx_ptr->rawtx_fields, 0x00, sizeof(tx_ptr->rawtx_fields));
// Re-use Ethereum transaction initialization
result = BoatEthTxInit( (BoatEthWallet *)wallet_ptr,
(BoatEthTx *)tx_ptr,
is_sync_tx,
gasprice_str,
gaslimit_str,
recipient_str );
if( result != BOAT_SUCCESS )
{
return BOAT_ERROR;
}
// Set transaction type
result = BoatPlatoneTxSetTxtype(tx_ptr, txtype);
if( result != BOAT_SUCCESS )
{
return BOAT_ERROR;
}
return BOAT_SUCCESS;
}
/******************************************************************************
@brief Transfer PlatONE value to spceified recipient
Function: BoatPlatoneTransfer()
This function transfer PlatONE value from the wallet's owner account to the
specified recipient account.
Before calling this function, all necessary wallet fields such as private key,
node URL and etc. must be set correctly.
@return
This function returns BOAT_SUCCESS if transfer is successful.\n
Otherwise it returns one of the error codes.
@param[in] tx_ptr
Transaction pointer.
@param[in] value_hex_str
A string representing the value (Unit: wei) to transfer, in HEX format like\n
"0x89AB3C".\n
Note that decimal value is not accepted. If a decimal value such as "1234"\n
is specified, it's treated as "0x1234".
*******************************************************************************/
BOAT_RESULT BoatPlatoneTransfer(BoatPlatoneTx *tx_ptr, BCHAR * value_hex_str)
{
BoatFieldMax32B value;
BoatFieldVariable data;
BUINT64 tx_type_big;
BOAT_RESULT result;
if( tx_ptr == NULL || tx_ptr->wallet_ptr == NULL || value_hex_str == NULL )
{
BoatLog(BOAT_LOG_NORMAL, "Argument cannot be NULL.");
return BOAT_ERROR_INVALID_ARGUMENT;
}
// Set nonce
result = BoatPlatoneTxSetNonce(tx_ptr, BOAT_PLATONE_NONCE_AUTO);
if( result != BOAT_SUCCESS ) return BOAT_ERROR;
// Set value
value.field_len =
UtilityHex2Bin(
value.field,
32,
value_hex_str,
TRIMBIN_LEFTTRIM,
BOAT_TRUE
);
result = BoatPlatoneTxSetValue(tx_ptr, &value);
if( result != BOAT_SUCCESS ) return BOAT_ERROR;
// Set data (contains txtype only)
UtilityUint64ToBigend(
(BUINT8*)&tx_type_big,
0,
TRIMBIN_TRIM_NO
);
data.field_ptr = (BUINT8*)&tx_type_big;
data.field_len = sizeof(BUINT64);
result = BoatPlatoneTxSetData(tx_ptr, &data);
if( result != BOAT_SUCCESS ) return BOAT_ERROR;
// Perform the transaction
// NOTE: Field v,r,s are calculated automatically
result = BoatPlatoneTxSend(tx_ptr);
if( result != BOAT_SUCCESS ) return BOAT_ERROR;
return BOAT_SUCCESS;
}
/******************************************************************************
@brief Call a state-less contract function
Function: BoatPlatoneCallContractFunc()
This function calls contract function that doesn't change the state of the
contract. "state" is the "global variable" used in a contract.
This function invokes the eth_call RPC method. eth_call method requests the
blockchain node to execute the function without affecting the block chain.
The execution runs only on the requested node thus it can return immediately
after the execution. This function synchronously return the return value
of the eth_call method, which is the return value of the contract function.
To call contract function that may change the state, use BoatPlatoneTxSend()
instead.
If call a contract function that may change the state with
BoatPlatoneCallContractFunc(), the function will be executed and return a value,
but none of the states will change.
@see BoatPlatoneTxSend()
@return
This function returns a HEX string representing the return value of the\n
called contract function.\n
If any error occurs, it returns NULL.
@param[in] tx_ptr
Transaction pointer
@param[in] rlp_param_ptr
A byte stream containing the parameters to pass to the function.\n
The stream is encoded in RLP format including the function name followed by\n
all parameters.
@param[in] rlp_param_len
Length of <rlp_param_ptr> in byte.
*******************************************************************************/
BCHAR * BoatPlatoneCallContractFunc(
BoatPlatoneTx *tx_ptr,
BUINT8 *rlp_param_ptr,
BUINT32 rlp_param_len)
{
// *2 for bin to HEX, + 3 for "0x" prefix and NULL terminator
BCHAR data_str[rlp_param_len*2 + 3]; // Compiler MUST support C99 to allow variable-size local array
Param_eth_call param_eth_call;
BCHAR *retval_str;
if( rlp_param_ptr == NULL && rlp_param_len != 0 )
{
BoatLog(BOAT_LOG_NORMAL, "Arguments cannot be NULL.");
return NULL;
}
BCHAR recipient_hexstr[BOAT_PLATONE_ADDRESS_SIZE*2+3];
UtilityBin2Hex(
recipient_hexstr,
tx_ptr->rawtx_fields.recipient,
BOAT_PLATONE_ADDRESS_SIZE,
BIN2HEX_LEFTTRIM_UNFMTDATA,
BIN2HEX_PREFIX_0x_YES,
BOAT_FALSE
);
param_eth_call.to = recipient_hexstr;
// Function call consumes zero gas but gasLimit and gasPrice must be specified.
param_eth_call.gas = "0x1fffff";
param_eth_call.gasPrice = "0x8250de00";
// Set function parameters
UtilityBin2Hex(
data_str,
rlp_param_ptr,
rlp_param_len,
BIN2HEX_LEFTTRIM_UNFMTDATA,
BIN2HEX_PREFIX_0x_YES,
BOAT_FALSE);
param_eth_call.data = data_str;
param_eth_call.block_num_str = "latest";
retval_str = web3_eth_call( tx_ptr->wallet_ptr->web3intf_context_ptr,
tx_ptr->wallet_ptr->network_info.node_url_ptr,
¶m_eth_call);
return retval_str;
}
#endif /* end of PROTOCOL_USE_PLATONE */
|
gitter-badger/BoAT-X-Framework | sdk/rpc/curlport.c | /******************************************************************************
* Copyright (C) 2018-2021 aitos.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/*!@brief libcurl porting for RPC
@file
curlport.c is the libcurl porting of RPC.
DO NOT call functions in this file directly. Instead call wrapper functions
provided by rpcport.
To use libcurl porting, RPC_USE_LIBCURL in boatoptions.h must set to 1.
*/
#include "boatinternal.h"
#if RPC_USE_LIBCURL == 1
#include "rpcport.h"
#include "curlport.h"
#include "curl/curl.h"
/*!*****************************************************************************
@brief Initialize libcurl.
Function: CurlPortInit()
This function initializes libcurl. It also dynamically allocates storage to
receive response from the peer.
@see CurlPortDeinit()
@return
This function returns a pointer to curlport context.\n
It returns NULL if initialization fails.
@param This function doesn't take any argument.
*******************************************************************************/
CurlPortContext * CurlPortInit(void)
{
CurlPortContext *curlport_context_ptr;
curlport_context_ptr = BoatMalloc(sizeof(CurlPortContext));
if( curlport_context_ptr == NULL )
{
BoatLog(BOAT_LOG_CRITICAL, "Fail to allocate Curl Context.");
}
else
{
curlport_context_ptr->curlport_response.string_space = CURLPORT_RECV_BUF_SIZE_STEP;
curlport_context_ptr->curlport_response.string_len = 0;
curlport_context_ptr->curlport_response.string_ptr = BoatMalloc(CURLPORT_RECV_BUF_SIZE_STEP);
if( curlport_context_ptr->curlport_response.string_ptr == NULL )
{
BoatLog(BOAT_LOG_CRITICAL, "Fail to allocate Curl RESPONSE buffer.");
BoatFree(curlport_context_ptr);
curlport_context_ptr = NULL;
}
}
return curlport_context_ptr;
}
/*!*****************************************************************************
@brief Deinitialize libcurl.
Function: CurlPortDeinit()
This function de-initializes libcurl. It also frees the dynamically
allocated storage to receive response from the peer.
@see CurlPortInit()
@return
This function doesn't return any value.
@param[in] curlport_context_ptr
Pointer to the context of curlport, which is returned by CurlPortInit()
*******************************************************************************/
void CurlPortDeinit(CurlPortContext * curlport_context_ptr)
{
if( curlport_context_ptr == NULL )
{
return;
}
curlport_context_ptr->curlport_response.string_space = 0;
curlport_context_ptr->curlport_response.string_len = 0;
if( curlport_context_ptr->curlport_response.string_ptr != NULL )
{
BoatFree(curlport_context_ptr->curlport_response.string_ptr);
}
curlport_context_ptr->curlport_response.string_ptr = NULL;
BoatFree(curlport_context_ptr);
return;
}
/*!*****************************************************************************
@brief Set options for use with libcurl.
Function: CurlPortSetOpt()
This function is a dummy function and does nothing.
@return
This function always returns BOAT_SUCCESS.
@param[in] curlport_context_ptr
A pointer to the curlport context
@param[in] remote_url_str
The URL of the remote server.
*******************************************************************************/
BOAT_RESULT CurlPortSetOpt(CurlPortContext * curlport_context_ptr, BCHAR *remote_url_str)
{
if( curlport_context_ptr == NULL || remote_url_str == NULL)
{
return BOAT_ERROR_NULL_POINTER;
}
curlport_context_ptr->remote_url_str = remote_url_str;
return BOAT_SUCCESS;
}
/*!*****************************************************************************
@brief Callback function to write received data from the peer to the user specified buffer.
Function: CurlPortWriteMemoryCallback()
This function is a callback function as per libcurl CURLOPT_WRITEFUNCTION option.
libcurl will call this function (possibly) multiple times to write received
data from peer to the buffer specified by this function. The received data
are typically some RESPONSE from the HTTP server.
The receiving buffer is dynamically allocated. If the received data from
the peer exceeds the current buffer size, a new buffer that could hold all
data will be allocated and previously received data will be copied to the
new buffer as well as the newly received data.
@see https://curl.haxx.se/libcurl/c/CURLOPT_WRITEFUNCTION.html
@return
This function returns how many bytes are written into the user buffer.
If the returned size differs from <size>*<nmemb>, libcurl will treat it as
a failure.
@param[in] data_ptr
A pointer given by libcurl, pointing to the received data from peer.
@param[in] size
For historic reasons, libcurl will always call with <size> = 1.
@param[in] nmemb
<nmemb> is the size of the data chunk to write. It doesn't include null
terminator even if the data were string.\n
For backward compatibility, use <size> * <nmemb> to calculate the size of
the received data.
@param[in] userdata
<userdata> is the value previously set by CURLOPT_WRITEDATA option.
Typically it's a pointer to a struct which contains information about the
receiving buffer.
*******************************************************************************/
size_t CurlPortWriteMemoryCallback(void *data_ptr, size_t size, size_t nmemb, void *userdata)
{
size_t data_size;
StringWithLen *mem;
BUINT32 expand_size;
BUINT32 expand_steps;
BCHAR *expanded_str;
BUINT32 expanded_to_space;
mem = (StringWithLen*)userdata;
// NOTE: For historic reasons, argument size is always 1 and nmemb is the
// size of the data chunk to write. And size * nmemb doesn't include null
// terminator even if the data were string.
data_size = size * nmemb;
// If response buffer has enough space:
if( mem->string_space - mem->string_len > data_size ) // 1 more byte reserved for null terminator
{
memcpy(mem->string_ptr + mem->string_len, data_ptr, data_size);
mem->string_len += data_size;
mem->string_ptr[mem->string_len] = '\0';
}
else // If response buffer has no enough space
{
// If malloc is supported, expand the response buffer in steps of
// CURLPORT_RECV_BUF_SIZE_STEP.
expand_size = data_size - (mem->string_space - mem->string_len) + 1; // plus 1 for null terminator
expand_steps = (expand_size - 1) / CURLPORT_RECV_BUF_SIZE_STEP + 1;
expanded_to_space = expand_steps * CURLPORT_RECV_BUF_SIZE_STEP + mem->string_space;
expanded_str = BoatMalloc(expanded_to_space);
if( expanded_str != NULL )
{
memcpy(expanded_str, mem->string_ptr, mem->string_len);
memcpy(expanded_str + mem->string_len, data_ptr, data_size);
BoatFree(mem->string_ptr);
mem->string_ptr = expanded_str;
mem->string_space = expanded_to_space;
mem->string_len += data_size;
mem->string_ptr[mem->string_len] = '\0';
}
}
return data_size;
}
/*!*****************************************************************************
@brief Perform a synchronous HTTP POST and wait for its response.
Function: CurlPortRequestSync()
This function initiates a curl session, performs a synchronous HTTP POST
and waits for its response.
@see https://curl.haxx.se/libcurl/c/curl_easy_setopt.html
@see https://curl.haxx.se/libcurl/c/curl_easy_perform.html
@return
This function returns BOAT_SUCCESS if succeeds.
Otherwise it returns one of the error codes.
@param[in] curlport_context_ptr
A pointer to the curlport context.
@param[in] request_str
A pointer to the request string to POST.
@param[in] request_len
The length of <request_str> excluding NULL terminator. This function is
wrapped by RpcRequestSync() and thus takes this argument for compatibility
with the wrapper function. Typically it equals to strlen(request_str).
@param[out] response_str_ptr
The address of a BCHAR* pointer (i.e. a double pointer) to hold the address
of the receiving buffer.\n
The receiving buffer is internally maintained by curlport and the caller
shall only read from the buffer. DO NOT modify the buffer or save the address
for later use.
@param[out] response_len_ptr
The address of a BUINT32 integer to hold the effective length of
<response_str_ptr> excluding NULL terminator. This function is wrapped by
RpcRequestSync() and thus takes this argument for compatibility with the
wrapper function. Typically it equals to strlen(response_str_ptr).
*******************************************************************************/
BOAT_RESULT CurlPortRequestSync(CurlPortContext * curlport_context_ptr,
const BCHAR *request_str,
BUINT32 request_len,
BOAT_OUT BCHAR **response_str_ptr,
BOAT_OUT BUINT32 *response_len_ptr)
{
CURL *curl_ctx_ptr = NULL;
struct curl_slist *curl_opt_list_ptr = NULL;
CURLcode curl_result;
long info;
BOAT_RESULT result = BOAT_ERROR;
boat_try_declare;
if( curlport_context_ptr == NULL
|| request_str == NULL
|| response_str_ptr == NULL
|| response_len_ptr == NULL )
{
BoatLog(BOAT_LOG_CRITICAL, "Argument cannot be NULL.");
result = BOAT_ERROR;
boat_throw(BOAT_ERROR_NULL_POINTER, CurlPortRequestSync_cleanup);
}
curl_ctx_ptr = curl_easy_init();
if(curl_ctx_ptr == NULL)
{
BoatLog(BOAT_LOG_CRITICAL, "curl_easy_init() fails.");
result = BOAT_ERROR_EXT_MODULE_OPERATION_FAIL;
boat_throw(BOAT_ERROR_EXT_MODULE_OPERATION_FAIL, CurlPortRequestSync_cleanup);
}
// Set RPC URL in format "<protocol>://<target name or IP>:<port>". e.g. "http://192.168.56.1:7545"
curl_result = curl_easy_setopt(curl_ctx_ptr, CURLOPT_URL, curlport_context_ptr->remote_url_str);
if( curl_result != CURLE_OK )
{
BoatLog(BOAT_LOG_NORMAL, "Unknown URL: %s", curlport_context_ptr->remote_url_str);
boat_throw(BOAT_ERROR_EXT_MODULE_OPERATION_FAIL, CurlPortRequestSync_cleanup);
}
// Configure all protocols to be supported
curl_easy_setopt(curl_ctx_ptr, CURLOPT_PROTOCOLS, CURLPROTO_ALL);
// Configure SSL Certification Verification
// If certification file is not available, set them to 0.
// See: https://curl.haxx.se/libcurl/c/CURLOPT_SSL_VERIFYPEER.html
curl_easy_setopt(curl_ctx_ptr, CURLOPT_SSL_VERIFYPEER, 0);
curl_easy_setopt(curl_ctx_ptr, CURLOPT_SSL_VERIFYHOST, 0);
// To specify a certificate file or specify a path containing certification files
// Only make sense when CURLOPT_SSL_VERIFYPEER is set to non-zero.
// curl_easy_setopt(curl_ctx_ptr, CURLOPT_CAINFO, "/etc/certs/cabundle.pem");
// curl_easy_setopt(curl_ctx_ptr, CURLOPT_CAPATH, "/etc/cert-dir");
// Allow Re-direction
curl_easy_setopt(curl_ctx_ptr, CURLOPT_FOLLOWLOCATION,1);
// Verbose Debug Info.
// curl_easy_setopt(curl_ctx_ptr, CURLOPT_VERBOSE, 1);
// Set HTTP Type: POST
curl_easy_setopt(curl_ctx_ptr, CURLOPT_POST, 1L);
// Set redirection: No
curl_easy_setopt(curl_ctx_ptr, CURLOPT_FOLLOWLOCATION, 0);
// Set entire curl timeout in millisecond. This time includes DNS resloving.
curl_easy_setopt(curl_ctx_ptr, CURLOPT_TIMEOUT_MS, 30000L);
// Set Connection timeout in millisecond
curl_easy_setopt(curl_ctx_ptr, CURLOPT_CONNECTTIMEOUT_MS, 10000L);
// Set HTTP HEADER Options
curl_opt_list_ptr = curl_slist_append(curl_opt_list_ptr,"Content-Type:application/json;charset=UTF-8");
if( curl_opt_list_ptr == NULL ) boat_throw(BOAT_ERROR_EXT_MODULE_OPERATION_FAIL, CurlPortRequestSync_cleanup);
curl_opt_list_ptr = curl_slist_append(curl_opt_list_ptr,"Accept:application/json, text/javascript, */*;q=0.01");
if( curl_opt_list_ptr == NULL ) boat_throw(BOAT_ERROR_EXT_MODULE_OPERATION_FAIL, CurlPortRequestSync_cleanup);
curl_opt_list_ptr = curl_slist_append(curl_opt_list_ptr,"Accept-Language:zh-CN,zh;q=0.8");
if( curl_opt_list_ptr == NULL ) boat_throw(BOAT_ERROR_EXT_MODULE_OPERATION_FAIL, CurlPortRequestSync_cleanup);
curl_easy_setopt(curl_ctx_ptr, CURLOPT_HTTPHEADER, curl_opt_list_ptr);
// Set callback and receive buffer for RESPONSE
// Clean up response buffer
curlport_context_ptr->curlport_response.string_ptr[0] = '\0';
curlport_context_ptr->curlport_response.string_len = 0;
curl_easy_setopt(curl_ctx_ptr, CURLOPT_WRITEDATA, &curlport_context_ptr->curlport_response);
curl_easy_setopt(curl_ctx_ptr, CURLOPT_WRITEFUNCTION, CurlPortWriteMemoryCallback);
// Set content to POST
curl_easy_setopt(curl_ctx_ptr, CURLOPT_POSTFIELDS, request_str);
curl_easy_setopt(curl_ctx_ptr, CURLOPT_POSTFIELDSIZE, request_len);
// Perform the RPC request
curl_result = curl_easy_perform(curl_ctx_ptr);
if( curl_result != CURLE_OK )
{
BoatLog(BOAT_LOG_NORMAL, "curl_easy_perform fails with CURLcode: %d.", curl_result);
boat_throw(BOAT_ERROR_EXT_MODULE_OPERATION_FAIL, CurlPortRequestSync_cleanup);
}
curl_result = curl_easy_getinfo(curl_ctx_ptr, CURLINFO_RESPONSE_CODE, &info);
if(( curl_result == CURLE_OK ) && (info == 200 || info == 201))
{
*response_str_ptr = curlport_context_ptr->curlport_response.string_ptr;
*response_len_ptr = curlport_context_ptr->curlport_response.string_len;
BoatLog(BOAT_LOG_VERBOSE, "Post: %s", request_str);
BoatLog(BOAT_LOG_VERBOSE, "Result Code: %ld", info);
BoatLog(BOAT_LOG_VERBOSE, "Response: %s", *response_str_ptr);
}
else
{
BoatLog(BOAT_LOG_NORMAL, "curl_easy_getinfo fails with CURLcode: %d, HTTP response code %ld.", curl_result, info);
boat_throw(BOAT_ERROR_EXT_MODULE_OPERATION_FAIL, CurlPortRequestSync_cleanup);
}
// Clean Up
curl_slist_free_all(curl_opt_list_ptr);
curl_easy_cleanup(curl_ctx_ptr);
result = BOAT_SUCCESS;
// Exceptional Clean Up
boat_catch(CurlPortRequestSync_cleanup)
{
BoatLog(BOAT_LOG_NORMAL, "Exception: %d", boat_exception);
if( curl_opt_list_ptr != NULL )
{
curl_slist_free_all(curl_opt_list_ptr);
}
if( curl_ctx_ptr != NULL )
{
curl_easy_cleanup(curl_ctx_ptr);
}
result = boat_exception;
}
return result;
}
#endif // end of #if RPC_USE_LIBCURL == 1
|
gitter-badger/BoAT-X-Framework | tests/case_15_platone_fun.c | /******************************************************************************
* Copyright (C) 2018-2021 aitos.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "boatiotsdk.h"
#include "my_contract.cpp.abi.h"
#include "testcommon.h"
//BoatDisplayTestResult(is_pass, case_name_str)
#define TEST_PONE_GASPRICE_0 "0x111111"
#define TEST_PONE_GASPRICE_1 "0x222222"
#define TEST_PONE_GASLIMIT_0 "0x333333"
#define TEST_PONE_GASLIMIT_1 "0x222222"
#define TEST_PONE_GASLIMIT_2 "0x111111"
//Contract Address
#define TEST_PONE_CONTRACT_ADDR_0 "0x1234567812345678123456781234567812345678"
#define TEST_PONE_CONTRACT_ADDR_1 "0x1234567812345678123456781234567812345688"
#define TEST_PONE_PRIVATE_KEY_0 "0x1234567812345678123456781234567812345678123456781234567812345678"
#define TEST_PONE_PRIVATE_KEY_1 "0x1234567812345678123456781234567812345678123456781234567812345688"
#define TEST_PONE_NODE_URL_0 "HTTP://127.0.0.1:7545"
#define TEST_PONE_NODE_URL_1 "HTTP://127.1.1.1:7545"
#define TEST_PONE_WALLET_NAME_0 "./tests/platone.key"
#define TEST_PONE_WALLET_NAME_1 "./tests/platone/platone.key"
#define TEST_PONE_PROTOCOL_0 BOAT_PROTOCOL_PLATONE
#define TEST_PONE_PROTOCOL_1 BOAT_PROTOCOL_ETHEREUM
BoatPlatoneWallet *g_case_15_platone_wallet_ptr;
//case 0:
BOAT_RESULT Case_15_PlatonePreCondition_0(BSINT8 *wallet_num)
{
BSINT32 index;
BoatPlatoneWalletConfig wallet_config;
BoatPlatoneWallet *wallet_ptr;
// Set Private Key
UtilityHex2Bin( wallet_config.priv_key_array,
32,
TEST_PONE_PRIVATE_KEY_0,
TRIMBIN_TRIM_NO,
BOAT_FALSE);
wallet_config.chain_id = 1;
wallet_config.eip155_compatibility = 0;
// Set Node URL
wallet_config.node_url_str[BOAT_NODE_URL_MAX_LEN-1] = '\0';
strncpy(wallet_config.node_url_str, TEST_PONE_NODE_URL_0, BOAT_NODE_URL_MAX_LEN-1);
index = BoatWalletCreate(TEST_PONE_PROTOCOL_0, TEST_PONE_WALLET_NAME_0, &wallet_config, sizeof(BoatPlatoneWalletConfig));
if( index == -1 )
{
BoatLog(BOAT_LOG_NORMAL, "Fail to create wallet.");
return BOAT_ERROR;
}
wallet_ptr = BoatGetWalletByIndex(index);
g_case_15_platone_wallet_ptr = wallet_ptr;
// Destroy private key in local variable
memset(wallet_config.priv_key_array, 0x00, 32);
*wallet_num = index;
return BOAT_SUCCESS;
}
BOAT_RESULT Case_15_Call_my_contract_0(BoatPlatoneWallet *wallet_ptr)
{
BCHAR *result_str;
BoatPlatoneTx tx_ctx;
BOAT_RESULT result;
// Set Contract Address
result = BoatPlatoneTxInit(wallet_ptr,
&tx_ctx,
BOAT_TRUE,
NULL,
TEST_PONE_GASLIMIT_0,
TEST_PONE_CONTRACT_ADDR_0,
BOAT_PLATONE_TX_TYPE_CONTRACT_NULL_TERMED_STR);
if( result != BOAT_SUCCESS )
{
BoatLog(BOAT_LOG_NORMAL, "BoatPlatoneTxInit fails.");
return BOAT_ERROR;
}
result_str = my_contract_cpp_abi_setName(&tx_ctx, "HelloWorld");
if( result_str != NULL )
{
BoatLog(BOAT_LOG_NORMAL, "setName returns: %s", result_str);
}
else
{
return BOAT_ERROR;
}
result_str = my_contract_cpp_abi_getName(&tx_ctx);
if( result_str != NULL )
{
BoatLog(BOAT_LOG_NORMAL, "getName returns: %s", result_str);
BoatDisplayTestResult( 0 == memcmp(result_str,"0x48656c6c6f576f726c64",strlen("0x48656c6c6f576f726c64")), "my_contract_cpp_abi_getName" );
}
else
{
return BOAT_ERROR;
}
return BOAT_SUCCESS;
}
BOAT_RESULT Case_15_PlatoneFunTest_0(BSINT8 *wallet_num)
{
BoatDisplayTestResult( BOAT_SUCCESS == Case_15_PlatonePreCondition_0(wallet_num), "Case_15_PlatonePreCondition_0" );
BoatDisplayTestResult( BOAT_SUCCESS == Case_15_Call_my_contract_0(g_case_15_platone_wallet_ptr), "Case_15_Call_my_contract_0" );
return BOAT_SUCCESS;
}
//case 1:load wallet
BOAT_RESULT Case_15_PlatonePreCondition_1(BSINT8 *wallet_num)
{
BSINT32 index;
BoatPlatoneWallet *wallet_ptr;
index = BoatWalletCreate(TEST_PONE_PROTOCOL_0, TEST_PONE_WALLET_NAME_0, NULL, sizeof(BoatPlatoneWalletConfig));
if( index == -1 )
{
BoatLog(BOAT_LOG_NORMAL, "Fail to create wallet.");
return BOAT_ERROR;
}
wallet_ptr = BoatGetWalletByIndex(index);
g_case_15_platone_wallet_ptr = wallet_ptr;
*wallet_num = index;
return BOAT_SUCCESS;
}
BOAT_RESULT Case_15_PlatoneFunTest_1(BSINT8 *wallet_num)
{
BoatDisplayTestResult( BOAT_SUCCESS == Case_15_PlatonePreCondition_1(wallet_num), "Case_15_PlatonePreCondition_1" );
BoatDisplayTestResult( BOAT_SUCCESS == Case_15_Call_my_contract_0(g_case_15_platone_wallet_ptr), "Case_15_Call_my_contract_0" );
return BOAT_SUCCESS;
}
//case 2:no private_key
BOAT_RESULT Case_15_PlatonePreCondition_2(BSINT8 *wallet_num)
{
BSINT32 index;
BoatPlatoneWalletConfig wallet_config;
BoatPlatoneWallet *wallet_ptr;
wallet_config.chain_id = 1;
wallet_config.eip155_compatibility = 0;
// Set Node URL
wallet_config.node_url_str[BOAT_NODE_URL_MAX_LEN-1] = '\0';
strncpy(wallet_config.node_url_str, TEST_PONE_NODE_URL_0, BOAT_NODE_URL_MAX_LEN-1);
index = BoatWalletCreate(TEST_PONE_PROTOCOL_0, NULL, &wallet_config, sizeof(BoatPlatoneWalletConfig));
if( index == -1 )
{
BoatLog(BOAT_LOG_NORMAL, "Fail to create wallet.");
return BOAT_ERROR;
}
wallet_ptr = BoatGetWalletByIndex(index);
g_case_15_platone_wallet_ptr = wallet_ptr;
// Destroy private key in local variable
memset(wallet_config.priv_key_array, 0x00, 32);
*wallet_num = index;
return BOAT_SUCCESS;
}
BOAT_RESULT Case_15_PlatoneFunTest_2(BSINT8 *wallet_num)
{
BoatDisplayTestResult( BOAT_SUCCESS == Case_15_PlatonePreCondition_2(wallet_num), "Case_15_PlatonePreCondition_2" );
BoatDisplayTestResult( BOAT_SUCCESS == Case_15_Call_my_contract_0(g_case_15_platone_wallet_ptr), "Case_15_Call_my_contract_0" );
return BOAT_SUCCESS;
}
//case 3:other private_key
BOAT_RESULT Case_15_PlatonePreCondition_3(BSINT8 *wallet_num)
{
BSINT32 index;
BoatPlatoneWalletConfig wallet_config;
BoatPlatoneWallet *wallet_ptr;
// Set Private Key
UtilityHex2Bin( wallet_config.priv_key_array,
32,
TEST_PONE_PRIVATE_KEY_1,
TRIMBIN_TRIM_NO,
BOAT_FALSE);
wallet_config.chain_id = 1;
wallet_config.eip155_compatibility = 0;
// Set Node URL
wallet_config.node_url_str[BOAT_NODE_URL_MAX_LEN-1] = '\0';
strncpy(wallet_config.node_url_str, TEST_PONE_NODE_URL_0, BOAT_NODE_URL_MAX_LEN-1);
index = BoatWalletCreate(TEST_PONE_PROTOCOL_0, NULL, &wallet_config, sizeof(BoatPlatoneWalletConfig));
if( index == -1 )
{
BoatLog(BOAT_LOG_NORMAL, "Fail to create wallet.");
return BOAT_ERROR;
}
wallet_ptr = BoatGetWalletByIndex(index);
g_case_15_platone_wallet_ptr = wallet_ptr;
// Destroy private key in local variable
memset(wallet_config.priv_key_array, 0x00, 32);
*wallet_num = index;
return BOAT_SUCCESS;
}
BOAT_RESULT Case_15_PlatoneFunTest_3(BSINT8 *wallet_num)
{
BoatDisplayTestResult( BOAT_SUCCESS == Case_15_PlatonePreCondition_3(wallet_num), "Case_15_PlatonePreCondition_3" );
BoatDisplayTestResult( BOAT_SUCCESS == Case_15_Call_my_contract_0(g_case_15_platone_wallet_ptr), "Case_15_Call_my_contract_0" );
return BOAT_SUCCESS;
}
//case 4:chain id
BOAT_RESULT Case_15_PlatonePreCondition_4(BSINT8 *wallet_num)
{
BSINT32 index;
BoatPlatoneWalletConfig wallet_config;
BoatPlatoneWallet *wallet_ptr;
// Set Private Key
UtilityHex2Bin( wallet_config.priv_key_array,
32,
TEST_PONE_PRIVATE_KEY_1,
TRIMBIN_TRIM_NO,
BOAT_FALSE);
wallet_config.chain_id = 0;
wallet_config.eip155_compatibility = 0;
// Set Node URL
wallet_config.node_url_str[BOAT_NODE_URL_MAX_LEN-1] = '\0';
strncpy(wallet_config.node_url_str, TEST_PONE_NODE_URL_0, BOAT_NODE_URL_MAX_LEN-1);
index = BoatWalletCreate(TEST_PONE_PROTOCOL_0, NULL, &wallet_config, sizeof(BoatPlatoneWalletConfig));
if( index == -1 )
{
BoatLog(BOAT_LOG_NORMAL, "Fail to create wallet.");
return BOAT_ERROR;
}
wallet_ptr = BoatGetWalletByIndex(index);
g_case_15_platone_wallet_ptr = wallet_ptr;
// Destroy private key in local variable
memset(wallet_config.priv_key_array, 0x00, 32);
*wallet_num = index;
return BOAT_SUCCESS;
}
BOAT_RESULT Case_15_PlatoneFunTest_4(BSINT8 *wallet_num)
{
BoatDisplayTestResult( BOAT_SUCCESS == Case_15_PlatonePreCondition_4(wallet_num), "Case_15_PlatonePreCondition_4" );
BoatDisplayTestResult( BOAT_SUCCESS == Case_15_Call_my_contract_0(g_case_15_platone_wallet_ptr), "Case_15_Call_my_contract_0" );
return BOAT_SUCCESS;
}
//case 5:EIP155
BOAT_RESULT Case_15_PlatonePreCondition_5(BSINT8 *wallet_num)
{
BSINT32 index;
BoatPlatoneWalletConfig wallet_config;
BoatPlatoneWallet *wallet_ptr;
// Set Private Key
UtilityHex2Bin( wallet_config.priv_key_array,
32,
TEST_PONE_PRIVATE_KEY_0,
TRIMBIN_TRIM_NO,
BOAT_FALSE);
wallet_config.chain_id = 1;
wallet_config.eip155_compatibility = 1;
// Set Node URL
wallet_config.node_url_str[BOAT_NODE_URL_MAX_LEN-1] = '\0';
strncpy(wallet_config.node_url_str, TEST_PONE_NODE_URL_0, BOAT_NODE_URL_MAX_LEN-1);
index = BoatWalletCreate(TEST_PONE_PROTOCOL_0, NULL, &wallet_config, sizeof(BoatPlatoneWalletConfig));
if( index == -1 )
{
BoatLog(BOAT_LOG_NORMAL, "Fail to create wallet.");
return BOAT_ERROR;
}
wallet_ptr = BoatGetWalletByIndex(index);
g_case_15_platone_wallet_ptr = wallet_ptr;
// Destroy private key in local variable
memset(wallet_config.priv_key_array, 0x00, 32);
*wallet_num = index;
return BOAT_SUCCESS;
}
BOAT_RESULT Case_15_PlatoneFunTest_5(BSINT8 *wallet_num)
{
BoatDisplayTestResult( BOAT_SUCCESS == Case_15_PlatonePreCondition_5(wallet_num), "Case_15_PlatonePreCondition_5" );
BoatDisplayTestResult( BOAT_SUCCESS == Case_15_Call_my_contract_0(g_case_15_platone_wallet_ptr), "Case_15_Call_my_contract_0" );
return BOAT_SUCCESS;
}
//case 6:url
BOAT_RESULT Case_15_PlatonePreCondition_6(BSINT8 *wallet_num)
{
BSINT32 index;
BoatPlatoneWalletConfig wallet_config;
BoatPlatoneWallet *wallet_ptr;
// Set Private Key
UtilityHex2Bin( wallet_config.priv_key_array,
32,
TEST_PONE_PRIVATE_KEY_0,
TRIMBIN_TRIM_NO,
BOAT_FALSE);
wallet_config.chain_id = 1;
wallet_config.eip155_compatibility = 0;
// Set Node URL
wallet_config.node_url_str[BOAT_NODE_URL_MAX_LEN-1] = '\0';
strncpy(wallet_config.node_url_str, TEST_PONE_NODE_URL_1, BOAT_NODE_URL_MAX_LEN-1);
index = BoatWalletCreate(TEST_PONE_PROTOCOL_0, NULL, &wallet_config, sizeof(BoatPlatoneWalletConfig));
if( index == -1 )
{
BoatLog(BOAT_LOG_NORMAL, "Fail to create wallet.");
return BOAT_ERROR;
}
wallet_ptr = BoatGetWalletByIndex(index);
g_case_15_platone_wallet_ptr = wallet_ptr;
// Destroy private key in local variable
memset(wallet_config.priv_key_array, 0x00, 32);
*wallet_num = index;
return BOAT_SUCCESS;
}
BOAT_RESULT Case_15_PlatoneFunTest_6(BSINT8 *wallet_num)
{
BoatDisplayTestResult( BOAT_SUCCESS == Case_15_PlatonePreCondition_6(wallet_num), "Case_15_PlatonePreCondition_6" );
BoatDisplayTestResult( BOAT_SUCCESS == Case_15_Call_my_contract_0(g_case_15_platone_wallet_ptr), "Case_15_Call_my_contract_0" );
return BOAT_SUCCESS;
}
//case 7:wallet_type
BOAT_RESULT Case_15_PlatonePreCondition_7(BSINT8 *wallet_num)
{
BSINT32 index;
BoatPlatoneWalletConfig wallet_config;
BoatPlatoneWallet *wallet_ptr;
// Set Private Key
UtilityHex2Bin( wallet_config.priv_key_array,
32,
TEST_PONE_PRIVATE_KEY_0,
TRIMBIN_TRIM_NO,
BOAT_FALSE);
wallet_config.chain_id = 1;
wallet_config.eip155_compatibility = 0;
// Set Node URL
wallet_config.node_url_str[BOAT_NODE_URL_MAX_LEN-1] = '\0';
strncpy(wallet_config.node_url_str, TEST_PONE_NODE_URL_0, BOAT_NODE_URL_MAX_LEN-1);
index = BoatWalletCreate(TEST_PONE_PROTOCOL_1, NULL, &wallet_config, sizeof(BoatPlatoneWalletConfig));
if( index == -1 )
{
BoatLog(BOAT_LOG_NORMAL, "Fail to create wallet.");
return BOAT_ERROR;
}
wallet_ptr = BoatGetWalletByIndex(index);
g_case_15_platone_wallet_ptr = wallet_ptr;
// Destroy private key in local variable
memset(wallet_config.priv_key_array, 0x00, 32);
*wallet_num = index;
return BOAT_SUCCESS;
}
BOAT_RESULT Case_15_PlatoneFunTest_7(BSINT8 *wallet_num)
{
BoatDisplayTestResult( BOAT_SUCCESS == Case_15_PlatonePreCondition_7(wallet_num), "Case_15_PlatonePreCondition_7" );
BoatDisplayTestResult( BOAT_SUCCESS == Case_15_Call_my_contract_0(g_case_15_platone_wallet_ptr), "Case_15_Call_my_contract_0" );
return BOAT_SUCCESS;
}
//case 8:one time
BOAT_RESULT Case_15_PlatonePreCondition_8(BSINT8 *wallet_num)
{
BSINT32 index;
BoatPlatoneWalletConfig wallet_config;
BoatPlatoneWallet *wallet_ptr;
// Set Private Key
UtilityHex2Bin( wallet_config.priv_key_array,
32,
TEST_PONE_PRIVATE_KEY_0,
TRIMBIN_TRIM_NO,
BOAT_FALSE);
wallet_config.chain_id = 1;
wallet_config.eip155_compatibility = 0;
// Set Node URL
wallet_config.node_url_str[BOAT_NODE_URL_MAX_LEN-1] = '\0';
strncpy(wallet_config.node_url_str, TEST_PONE_NODE_URL_0, BOAT_NODE_URL_MAX_LEN-1);
index = BoatWalletCreate(TEST_PONE_PROTOCOL_0, NULL, &wallet_config, sizeof(BoatPlatoneWalletConfig));
if( index == -1 )
{
BoatLog(BOAT_LOG_NORMAL, "Fail to create wallet.");
return BOAT_ERROR;
}
wallet_ptr = BoatGetWalletByIndex(index);
g_case_15_platone_wallet_ptr = wallet_ptr;
// Destroy private key in local variable
memset(wallet_config.priv_key_array, 0x00, 32);
*wallet_num = index;
return BOAT_SUCCESS;
}
BOAT_RESULT Case_15_PlatoneFunTest_8(BSINT8 *wallet_num)
{
BoatDisplayTestResult( BOAT_SUCCESS == Case_15_PlatonePreCondition_8(wallet_num), "Case_15_PlatonePreCondition_8" );
BoatDisplayTestResult( BOAT_SUCCESS == Case_15_Call_my_contract_0(g_case_15_platone_wallet_ptr), "Case_15_Call_my_contract_0" );
return BOAT_SUCCESS;
}
//case 9:is_sync_tx
BOAT_RESULT Case_15_Call_my_contract_9(BoatPlatoneWallet *wallet_ptr)
{
BCHAR *result_str;
BoatPlatoneTx tx_ctx;
// Set Contract Address
BoatDisplayTestResult( BOAT_SUCCESS == BoatPlatoneTxInit(wallet_ptr,&tx_ctx,BOAT_TRUE,NULL,TEST_PONE_GASLIMIT_0,TEST_PONE_CONTRACT_ADDR_0,BOAT_PLATONE_TX_TYPE_CONTRACT_NULL_TERMED_STR), "BoatPlatoneTxInit" );
BoatDisplayTestResult( BOAT_SUCCESS == ( result_str = my_contract_cpp_abi_setName(NULL, "HelloWorld")), "my_contract_cpp_abi_setName" );
BoatLog(BOAT_LOG_NORMAL, "setName returns: %s", result_str);
BoatDisplayTestResult( BOAT_SUCCESS == ( result_str = my_contract_cpp_abi_getName(&tx_ctx)), "my_contract_cpp_abi_getName" );
BoatLog(BOAT_LOG_NORMAL, "getName returns: %s", result_str);
BoatDisplayTestResult( 0 == memcmp(result_str,"0x48656c6c6f576f726c64",strlen("0x48656c6c6f576f726c64")), "my_contract_cpp_abi_getName" );
return BOAT_SUCCESS;
}
BOAT_RESULT Case_15_PlatoneFunTest_9(BSINT8 *wallet_num)
{
BoatDisplayTestResult( BOAT_SUCCESS == Case_15_PlatonePreCondition_0(wallet_num), "Case_15_PlatonePreCondition_0" );
BoatDisplayTestResult( BOAT_SUCCESS == Case_15_Call_my_contract_9(g_case_15_platone_wallet_ptr), "Case_15_Call_my_contract_9" );
return BOAT_SUCCESS;
}
//case 10:TEST_PONE_GASPRICE_1
BOAT_RESULT Case_15_Call_my_contract_10(BoatPlatoneWallet *wallet_ptr)
{
BCHAR *result_str;
BoatPlatoneTx tx_ctx;
// Set Contract Address
BoatDisplayTestResult( BOAT_SUCCESS == BoatPlatoneTxInit(wallet_ptr,&tx_ctx,BOAT_FALSE,TEST_PONE_GASPRICE_1,TEST_PONE_GASLIMIT_0,TEST_PONE_CONTRACT_ADDR_0,BOAT_PLATONE_TX_TYPE_CONTRACT_NULL_TERMED_STR), "BoatPlatoneTxInit" );
BoatDisplayTestResult( BOAT_SUCCESS == ( result_str = my_contract_cpp_abi_setName(NULL, "HelloWorld")), "my_contract_cpp_abi_setName" );
BoatLog(BOAT_LOG_NORMAL, "setName returns: %s", result_str);
BoatDisplayTestResult( BOAT_SUCCESS == ( result_str = my_contract_cpp_abi_getName(&tx_ctx)), "my_contract_cpp_abi_getName" );
BoatLog(BOAT_LOG_NORMAL, "getName returns: %s", result_str);
BoatDisplayTestResult( 0 == memcmp(result_str,"0x48656c6c6f576f726c64",strlen("0x48656c6c6f576f726c64")), "my_contract_cpp_abi_getName" );
return BOAT_SUCCESS;
}
BOAT_RESULT Case_15_PlatoneFunTest_10(BSINT8 *wallet_num)
{
BoatDisplayTestResult( BOAT_SUCCESS == Case_15_PlatonePreCondition_0(wallet_num), "Case_15_PlatonePreCondition_0" );
BoatDisplayTestResult( BOAT_SUCCESS == Case_15_Call_my_contract_10(g_case_15_platone_wallet_ptr), "Case_15_Call_my_contract_10" );
return BOAT_SUCCESS;
}
//case 11:TEST_PONE_GASLIMIT_1
BOAT_RESULT Case_15_Call_my_contract_11(BoatPlatoneWallet *wallet_ptr)
{
BCHAR *result_str;
BoatPlatoneTx tx_ctx;
// Set Contract Address
BoatDisplayTestResult( BOAT_SUCCESS == BoatPlatoneTxInit(wallet_ptr,&tx_ctx,BOAT_FALSE,TEST_PONE_GASPRICE_0,TEST_PONE_GASLIMIT_1,TEST_PONE_CONTRACT_ADDR_0,BOAT_PLATONE_TX_TYPE_CONTRACT_NULL_TERMED_STR), "BoatPlatoneTxInit" );
BoatDisplayTestResult( BOAT_SUCCESS == ( result_str = my_contract_cpp_abi_setName(NULL, "HelloWorld")), "my_contract_cpp_abi_setName" );
BoatLog(BOAT_LOG_NORMAL, "setName returns: %s", result_str);
BoatDisplayTestResult( BOAT_SUCCESS == ( result_str = my_contract_cpp_abi_getName(&tx_ctx)), "my_contract_cpp_abi_getName" );
BoatLog(BOAT_LOG_NORMAL, "getName returns: %s", result_str);
BoatDisplayTestResult( 0 == memcmp(result_str,"0x48656c6c6f576f726c64",strlen("0x48656c6c6f576f726c64")), "my_contract_cpp_abi_getName" );
return BOAT_SUCCESS;
}
BOAT_RESULT Case_15_PlatoneFunTest_11(BSINT8 *wallet_num)
{
BoatDisplayTestResult( BOAT_SUCCESS == Case_15_PlatonePreCondition_1(wallet_num), "Case_15_PlatonePreCondition_0" );
BoatDisplayTestResult( BOAT_SUCCESS == Case_15_Call_my_contract_0(g_case_15_platone_wallet_ptr), "Case_15_Call_my_contract_0" );
return BOAT_SUCCESS;
}
//case 11:TEST_PONE_CONTRACT_ADDR_1
BOAT_RESULT Case_15_Call_my_contract_12(BoatPlatoneWallet *wallet_ptr)
{
BCHAR *result_str;
BoatPlatoneTx tx_ctx;
// Set Contract Address
BoatDisplayTestResult( BOAT_SUCCESS == BoatPlatoneTxInit(wallet_ptr,&tx_ctx,BOAT_FALSE,TEST_PONE_GASPRICE_0,TEST_PONE_GASLIMIT_0,TEST_PONE_CONTRACT_ADDR_1,BOAT_PLATONE_TX_TYPE_CONTRACT_NULL_TERMED_STR), "BoatPlatoneTxInit" );
BoatDisplayTestResult( BOAT_SUCCESS == ( result_str = my_contract_cpp_abi_setName(NULL, "HelloWorld")), "my_contract_cpp_abi_setName" );
BoatLog(BOAT_LOG_NORMAL, "setName returns: %s", result_str);
BoatDisplayTestResult( BOAT_SUCCESS == ( result_str = my_contract_cpp_abi_getName(&tx_ctx)), "my_contract_cpp_abi_getName" );
BoatLog(BOAT_LOG_NORMAL, "getName returns: %s", result_str);
BoatDisplayTestResult( 0 == memcmp(result_str,"0x48656c6c6f576f726c64",strlen("0x48656c6c6f576f726c64")), "my_contract_cpp_abi_getName" );
return BOAT_SUCCESS;
}
BOAT_RESULT Case_15_PlatoneFunTest_12(BSINT8 *wallet_num)
{
BoatDisplayTestResult( BOAT_SUCCESS == Case_15_PlatonePreCondition_1(wallet_num), "Case_15_PlatonePreCondition_0" );
BoatDisplayTestResult( BOAT_SUCCESS == Case_15_Call_my_contract_0(g_case_15_platone_wallet_ptr), "Case_15_Call_my_contract_0" );
return BOAT_SUCCESS;
}
BOAT_RESULT Case_15_PlatONEMain(void)
{
BOAT_RESULT case_result = BOAT_SUCCESS;
BSINT8 wallet_num=0;
case_result += Case_15_PlatoneFunTest_0(&wallet_num);
BoatWalletUnload(wallet_num);
case_result += Case_15_PlatoneFunTest_1(&wallet_num);
BoatWalletUnload(wallet_num);
case_result += Case_15_PlatoneFunTest_2(&wallet_num);
BoatWalletUnload(wallet_num);
case_result += Case_15_PlatoneFunTest_3(&wallet_num);
BoatWalletUnload(wallet_num);
case_result += Case_15_PlatoneFunTest_4(&wallet_num);
BoatWalletUnload(wallet_num);
case_result += Case_15_PlatoneFunTest_5(&wallet_num);
BoatWalletUnload(wallet_num);
case_result += Case_15_PlatoneFunTest_6(&wallet_num);
BoatWalletUnload(wallet_num);
case_result += Case_15_PlatoneFunTest_7(&wallet_num);
BoatWalletUnload(wallet_num);
case_result += Case_15_PlatoneFunTest_8(&wallet_num);
BoatWalletUnload(wallet_num);
case_result += Case_15_PlatoneFunTest_9(&wallet_num);
BoatWalletUnload(wallet_num);
case_result += Case_15_PlatoneFunTest_10(&wallet_num);
BoatWalletUnload(wallet_num);
case_result += Case_15_PlatoneFunTest_11(&wallet_num);
BoatWalletUnload(wallet_num);
case_result += Case_15_PlatoneFunTest_12(&wallet_num);
BoatWalletUnload(wallet_num);
BoatLog(BOAT_LOG_NORMAL, "case_result: %d.", case_result);
//Delete wallet
BoatWalletDelete(TEST_PONE_WALLET_NAME_0);
return case_result;
}
|
gitter-badger/BoAT-X-Framework | include/boaterrcode.h | <gh_stars>1-10
/******************************************************************************
* Copyright (C) 2018-2021 aitos.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/*!@brief Error codes
@file
boaterrcode.h defines error codes.
*/
#ifndef __BOATERRCODE_H__
#define __BOATERRCODE_H__
#define BOAT_SUCCESS 0
#define BOAT_ERROR (-1)
#define BOAT_ERROR_NULL_POINTER (-100)
#define BOAT_ERROR_OUT_OF_MEMORY (-101)
#define BOAT_ERROR_INVALID_LENGTH (-102)
#define BOAT_ERROR_INCOMPATIBLE_ARGUMENTS (-103)
#define BOAT_ERROR_RLP_ENCODING_FAIL (-104)
#define BOAT_ERROR_EXT_MODULE_OPERATION_FAIL (-105)
#define BOAT_ERROR_JSON_PARSE_FAIL (-106)
#define BOAT_ERROR_RPC_FAIL (-107)
#define BOAT_ERROR_INVALID_ARGUMENT (-108)
#define BOAT_ERROR_BUFFER_EXHAUSTED (-109)
#define BOAT_ERROR_TX_NOT_MINED (-110)
#define BOAT_ERROR_TEST_CASE_FAIL (-1000)
#endif
|
gitter-badger/BoAT-X-Framework | tests/case_10_eth_fun.c | <reponame>gitter-badger/BoAT-X-Framework
/******************************************************************************
* Copyright (C) 2018-2021 aitos.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "boatinternal.h"
#include "StoreRead.h"
#include "testcommon.h"
#define TEST_ETH_GASPRICE_0 "0x111111"
#define TEST_ETH_GASPRICE_1 "0x222222"
#define TEST_ETH_GASLIMIT_0 "0x111111"
#define TEST_ETH_GASLIMIT_1 "0x222222"
#define TEST_ETH_GASLIMIT_2 "0x333333"
//Contract Address
#define TEST_ETH_CONTRACT_ADDR_0 "0x1234567812345678123456781234567812345678"
#define TEST_ETH_CONTRACT_ADDR_1 "0x1234567812345678123456781234567812341234"
//Recipient Address
#define TEST_ETH_RECIPIENT_ADDR_0 "0x1234123412341234123412341234123412341234"
#define TEST_ETH_RECIPIENT_ADDR_1 "0x1234123412341234123412341234123412345678"
#define TEST_ETH_PRIVATE_KEY_0 "0x1234567812345678123456781234567812345678123456781234567812345678"
#define TEST_ETH_PRIVATE_KEY_1 "0x1234123412341234123412341234123412341234123412341234123412341234"
#define TEST_ETH_NODE_URL_0 "HTTP://127.0.0.1:7545"
#define TEST_ETH_NODE_URL_1 "HTTP://127.1.1.1:7545"
#define TEST_ETH_WALLET_NAME_0 "./tests/eth.key"
#define TEST_ETH_WALLET_NAME_1 "./tests/eth/eth.key"
#define TEST_ETH_PROTOCOL_0 BOAT_PROTOCOL_ETHEREUM
#define TEST_ETH_PROTOCOL_1 BOAT_PROTOCOL_PLATONE
#define TEST_ETH_TRANSFER_ETH_0 "0x2386F26FC10000" // 0.01ETH or 1e16 wei, value
#define TEST_ETH_TRANSFER_ETH_1 "0xDE0B6B3A7640000" // 1ETH or 1e18 wei, value
#define TEST_ETH_TRANSFER_ETH_2 "0x29A2241AF62C0000" // 3ETH or 3e18 wei, value
BoatEthWallet *g_case_10_ethereum_wallet_ptr;
/*****************************************************************************************************************************************************************/
//test case 0:
BOAT_RESULT Case_10_EthereumPreCondition_0(BSINT8 *wallet_num)
{
BSINT32 index;
BoatEthWalletConfig wallet_config;
BoatEthWallet *wallet_ptr;
// Set Private Key
UtilityHex2Bin( wallet_config.priv_key_array,
32,
TEST_ETH_PRIVATE_KEY_0,
TRIMBIN_TRIM_NO,
BOAT_FALSE);
wallet_config.chain_id = 1;
wallet_config.eip155_compatibility = 0;
// Set Node URL
wallet_config.node_url_str[BOAT_NODE_URL_MAX_LEN-1] = '\0';
strncpy(wallet_config.node_url_str, TEST_ETH_NODE_URL_0, BOAT_NODE_URL_MAX_LEN-1);
// Create a new wallet or overwrite an existed wallet
index = BoatWalletCreate(TEST_ETH_PROTOCOL_0, TEST_ETH_WALLET_NAME_0, &wallet_config, sizeof(BoatEthWalletConfig));
if( index == -1 )
{
BoatLog(BOAT_LOG_NORMAL, "Fail to create wallet.");
return BOAT_ERROR;
}
wallet_ptr = BoatGetWalletByIndex(index);
g_case_10_ethereum_wallet_ptr = wallet_ptr;
*wallet_num = index;
return BOAT_SUCCESS;
}
BOAT_RESULT Case_10_EthereumTransfer_0(BoatEthWallet *wallet_ptr)
{
BoatEthTx tx_ctx;
// Set Recipient Address
BoatDisplayTestResult(BOAT_SUCCESS == BoatEthTxInit(wallet_ptr,&tx_ctx,BOAT_TRUE,TEST_ETH_GASPRICE_0,TEST_ETH_GASLIMIT_0,TEST_ETH_RECIPIENT_ADDR_0),"BoatEthTxInit");
BoatDisplayTestResult(BOAT_SUCCESS == BoatEthTransfer(&tx_ctx, TEST_ETH_TRANSFER_ETH_0),"BoatEthTransfer");
return BOAT_SUCCESS;
}
BOAT_RESULT Case_10_Call_ReadStore_0(BoatEthWallet *wallet_ptr)
{
BCHAR *result_str;
BUINT32 list_len;
BUINT32 index_u256_big[32/4];
BUINT8 result_buff[127];
BUINT32 index;
BoatEthTx tx_ctx;
// Set Contract Address
BoatDisplayTestResult(BOAT_SUCCESS == BoatEthTxInit(wallet_ptr,&tx_ctx,BOAT_TRUE,TEST_ETH_GASPRICE_0,TEST_ETH_GASLIMIT_0,TEST_ETH_CONTRACT_ADDR_0),"BoatEthTxInit");
BoatDisplayTestResult(NULL != (result_str = StoreRead_saveList(&tx_ctx, (BUINT8 *)"Hello world")),"StoreRead_saveList");
BoatLog(BOAT_LOG_NORMAL, "StoreRead_saveList returns: %s", result_str);
BoatDisplayTestResult(NULL != (result_str = StoreRead_readListLength(&tx_ctx)),"StoreRead_readListLength");
BoatLog(BOAT_LOG_NORMAL, "readListLength returns: %s", result_str);
UtilityHex2Bin((BUINT8*)index_u256_big,sizeof(index_u256_big),result_str,TRIMBIN_TRIM_NO,BOAT_FALSE);
UtilityChangeEndian(index_u256_big, sizeof(index_u256_big));
list_len = index_u256_big[0];
index = list_len-1;
BoatDisplayTestResult(NULL != (result_str = StoreRead_readListByIndex(&tx_ctx, index)),"StoreRead_readListByIndex");
BoatLog(BOAT_LOG_NORMAL, "StoreRead_readListByIndex returns: %s\n", result_str);
UtilityHex2Bin(result_buff,sizeof(result_buff),result_str,TRIMBIN_TRIM_NO, BOAT_FALSE);
BoatDisplayTestResult( 0 == memcmp(result_buff,"Hello world",strlen("Hello world")), "readListByIndex-memcmp" );
return BOAT_SUCCESS;
}
BOAT_RESULT Case_10_EthFunTest_0(BSINT8 *wallet_num)
{
BCHAR * balance_wei;
//A account
double balance_bef_a=0.0;
double balance_aft_a=0.0;
//B account
double balance_bef_b=0.0;
double balance_aft_b=0.0;
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_EthereumPreCondition_0(wallet_num), "PreCondition_0" );
//Balance of Account A before transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, NULL)), "Account A before the transfer" );
balance_bef_a = UtilityWeiStrToEthDouble(balance_wei);
//Balance of Account B before transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, TEST_ETH_RECIPIENT_ADDR_0)), "Account B before the transfer" );
balance_bef_b = UtilityWeiStrToEthDouble(balance_wei);
//Account A transfers 0.01ETH to Account B
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_EthereumTransfer_0(g_case_10_ethereum_wallet_ptr), "Case_10_EthereumTransfer_0" );
//Balance of account A after transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, NULL)), "After account A is transferred" );
balance_aft_a = UtilityWeiStrToEthDouble(balance_wei);
//Balance of account B after transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, TEST_ETH_RECIPIENT_ADDR_0)), "After account B is transferred " );
balance_aft_b = UtilityWeiStrToEthDouble(balance_wei);
//Calculate the difference before and after the transfer
BoatDisplayTestResult( ((balance_bef_a - balance_aft_a + 0.0001) >= UtilityWeiStrToEthDouble(TEST_ETH_TRANSFER_ETH_0)),"Case_10_EthereumTransfer A balance" );
BoatDisplayTestResult( ((balance_aft_b - balance_bef_b + 0.0001) >= UtilityWeiStrToEthDouble(TEST_ETH_TRANSFER_ETH_0)),"Case_10_EthereumTransfer B balance" );
//Call the contract
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_Call_ReadStore_0(g_case_10_ethereum_wallet_ptr), "ReadStore_0" );
return BOAT_SUCCESS;
}
//test case 1: no private key
BOAT_RESULT Case_10_EthereumPreCondition_1(BSINT8 *wallet_num)
{
BSINT32 index;
BoatEthWalletConfig wallet_config;
BoatEthWallet *wallet_ptr;
/* 1: The private key is not populated */
wallet_config.chain_id = 1;
wallet_config.eip155_compatibility = 0;
// Set Node URL
wallet_config.node_url_str[BOAT_NODE_URL_MAX_LEN-1] = '\0';
strncpy(wallet_config.node_url_str, TEST_ETH_NODE_URL_0, BOAT_NODE_URL_MAX_LEN-1);
// Create a new wallet or overwrite an existed wallet
index = BoatWalletCreate(TEST_ETH_PROTOCOL_0, TEST_ETH_WALLET_NAME_0, &wallet_config, sizeof(BoatEthWalletConfig));
if( index == -1 )
{
BoatLog(BOAT_LOG_NORMAL, "Fail to create wallet.");
return BOAT_ERROR;
}
wallet_ptr = BoatGetWalletByIndex(index);
g_case_10_ethereum_wallet_ptr = wallet_ptr;
*wallet_num = index;
return BOAT_SUCCESS;
}
BOAT_RESULT Case_10_EthFunTest_1(BSINT8 *wallet_num)
{
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_EthereumPreCondition_1(wallet_num), "[Case_10_EthFunTest_1]:PreCondition_1" );
return BOAT_SUCCESS;
}
//test case 2: other private key
BOAT_RESULT Case_10_EthereumPreCondition_2(BSINT8 *wallet_num)
{
BSINT32 index;
BoatEthWalletConfig wallet_config;
BoatEthWallet *wallet_ptr;
// Set Private Key
UtilityHex2Bin( wallet_config.priv_key_array,
32,
TEST_ETH_PRIVATE_KEY_1,
TRIMBIN_TRIM_NO,
BOAT_FALSE);
wallet_config.chain_id = 1;
wallet_config.eip155_compatibility = 0;
// Set Node URL
wallet_config.node_url_str[BOAT_NODE_URL_MAX_LEN-1] = '\0';
strncpy(wallet_config.node_url_str, TEST_ETH_NODE_URL_0, BOAT_NODE_URL_MAX_LEN-1);
// Create a new wallet or overwrite an existed wallet
index = BoatWalletCreate(TEST_ETH_PROTOCOL_0, TEST_ETH_WALLET_NAME_0, &wallet_config, sizeof(BoatEthWalletConfig));
if( index == -1 )
{
BoatLog(BOAT_LOG_NORMAL, "Fail to create wallet.");
return BOAT_ERROR;
}
wallet_ptr = BoatGetWalletByIndex(index);
g_case_10_ethereum_wallet_ptr = wallet_ptr;
*wallet_num = index;
return BOAT_SUCCESS;
}
BOAT_RESULT Case_10_EthFunTest_2(BSINT8 *wallet_num)
{
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_EthereumPreCondition_2(wallet_num), "[Case_10_EthFunTest_2]:PreCondition_2" );
//BCHAR * balance_wei;
//BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, NULL)), "Account A before the transfer" );
return BOAT_SUCCESS;
}
//test case 3:chain_id = 0
BOAT_RESULT Case_10_EthereumPreCondition_3(BSINT8 *wallet_num)
{
BSINT32 index;
BoatEthWalletConfig wallet_config;
BoatEthWallet *wallet_ptr;
// Set Private Key
UtilityHex2Bin( wallet_config.priv_key_array,
32,
TEST_ETH_PRIVATE_KEY_0,
TRIMBIN_TRIM_NO,
BOAT_FALSE);
wallet_config.chain_id = 0;
wallet_config.eip155_compatibility = 0;
// Set Node URL
wallet_config.node_url_str[BOAT_NODE_URL_MAX_LEN-1] = '\0';
strncpy(wallet_config.node_url_str, TEST_ETH_NODE_URL_0, BOAT_NODE_URL_MAX_LEN-1);
// Create a new wallet or overwrite an existed wallet
index = BoatWalletCreate(TEST_ETH_PROTOCOL_0, TEST_ETH_WALLET_NAME_0, &wallet_config, sizeof(BoatEthWalletConfig));
if( index == -1 )
{
BoatLog(BOAT_LOG_NORMAL, "Fail to create wallet.");
return BOAT_ERROR;
}
wallet_ptr = BoatGetWalletByIndex(index);
g_case_10_ethereum_wallet_ptr = wallet_ptr;
*wallet_num = index;
return BOAT_SUCCESS;
}
BOAT_RESULT Case_10_EthFunTest_3(BSINT8 *wallet_num)
{
BCHAR * balance_wei;
//A account
double balance_bef_a=0.0;
double balance_aft_a=0.0;
//B account
double balance_bef_b=0.0;
double balance_aft_b=0.0;
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_EthereumPreCondition_3(wallet_num), "[Case_10_EthFunTest_3]:PreCondition_3" );
//Balance of Account A before transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, NULL)), "Account A before the transfer" );
balance_bef_a = UtilityWeiStrToEthDouble(balance_wei);
//Balance of Account B before transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, TEST_ETH_RECIPIENT_ADDR_0)), "Account B before the transfer" );
balance_bef_b = UtilityWeiStrToEthDouble(balance_wei);
//Account A transfers 0.01ETH to Account B
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_EthereumTransfer_0(g_case_10_ethereum_wallet_ptr), "Case_10_EthereumTransfer_0" );
//Balance of account A after transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, NULL)), "After account A is transferred" );
balance_aft_a = UtilityWeiStrToEthDouble(balance_wei);
//Balance of account B after transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, TEST_ETH_RECIPIENT_ADDR_0)), "After account B is transferred" );
balance_aft_b = UtilityWeiStrToEthDouble(balance_wei);
//Calculate the difference before and after the transfer
BoatDisplayTestResult( ((balance_bef_a - balance_aft_a + 0.0001) >= UtilityWeiStrToEthDouble(TEST_ETH_TRANSFER_ETH_0)),"Case_10_EthereumTransfer A balance" );
BoatDisplayTestResult( ((balance_aft_b - balance_bef_b + 0.0001) >= UtilityWeiStrToEthDouble(TEST_ETH_TRANSFER_ETH_0)),"Case_10_EthereumTransfer B balance" );
//Call the contract
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_Call_ReadStore_0(g_case_10_ethereum_wallet_ptr), "Case_10_Call_ReadStore_0" );
return BOAT_SUCCESS;
}
//test case 4:URL = TEST_ETH_NODE_URL_1
BOAT_RESULT Case_10_EthereumPreCondition_4(BSINT8 *wallet_num)
{
BSINT32 index;
BoatEthWalletConfig wallet_config;
BoatEthWallet *wallet_ptr;
UtilityHex2Bin( wallet_config.priv_key_array,
32,
TEST_ETH_PRIVATE_KEY_0,
TRIMBIN_TRIM_NO,
BOAT_FALSE);
wallet_config.chain_id = 1;
wallet_config.eip155_compatibility = 0;
// Set Node URL
wallet_config.node_url_str[BOAT_NODE_URL_MAX_LEN-1] = '\0';
strncpy(wallet_config.node_url_str, TEST_ETH_NODE_URL_1, BOAT_NODE_URL_MAX_LEN-1);
// Create a new wallet or overwrite an existed wallet
index = BoatWalletCreate(TEST_ETH_PROTOCOL_0, TEST_ETH_WALLET_NAME_0, &wallet_config, sizeof(BoatEthWalletConfig));
if( index == -1 )
{
BoatLog(BOAT_LOG_NORMAL, "Fail to create wallet.");
return BOAT_ERROR;
}
wallet_ptr = BoatGetWalletByIndex(index);
g_case_10_ethereum_wallet_ptr = wallet_ptr;
*wallet_num = index;
return BOAT_SUCCESS;
}
BOAT_RESULT Case_10_EthFunTest_4(BSINT8 *wallet_num)
{
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_EthereumPreCondition_4(wallet_num), "[Case_10_EthFunTest_4]:PreCondition_4" );
//Get balance
BoatDisplayTestResult( NULL == BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, NULL), "BoatEthWalletGetBalance" );
return BOAT_SUCCESS;
}
//test case 5:eip155=1
BOAT_RESULT Case_10_EthereumPreCondition_5(BSINT8 *wallet_num)
{
BSINT32 index;
BoatEthWalletConfig wallet_config;
BoatEthWallet *wallet_ptr;
// Set Private Key
UtilityHex2Bin( wallet_config.priv_key_array,
32,
TEST_ETH_PRIVATE_KEY_0,
TRIMBIN_TRIM_NO,
BOAT_FALSE);
wallet_config.chain_id = 1;
wallet_config.eip155_compatibility = 1;
// Set Node URL
wallet_config.node_url_str[BOAT_NODE_URL_MAX_LEN-1] = '\0';
strncpy(wallet_config.node_url_str, TEST_ETH_NODE_URL_0, BOAT_NODE_URL_MAX_LEN-1);
// Create a new wallet or overwrite an existed wallet
index = BoatWalletCreate(TEST_ETH_PROTOCOL_0, TEST_ETH_WALLET_NAME_0, &wallet_config, sizeof(BoatEthWalletConfig));
if( index == -1 )
{
BoatLog(BOAT_LOG_NORMAL, "Fail to create wallet.");
return BOAT_ERROR;
}
wallet_ptr = BoatGetWalletByIndex(index);
g_case_10_ethereum_wallet_ptr = wallet_ptr;
*wallet_num = index;
return BOAT_SUCCESS;
}
BOAT_RESULT Case_10_EthFunTest_5(BSINT8 *wallet_num)
{
BCHAR * balance_wei;
//A account
double balance_bef_a=0.0;
double balance_aft_a=0.0;
//B account
double balance_bef_b=0.0;
double balance_aft_b=0.0;
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_EthereumPreCondition_5(wallet_num), "[Case_10_EthFunTest_5]:PreCondition_5" );
//Balance of Account A before transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, NULL)), "Account A before the transfer" );
balance_bef_a = UtilityWeiStrToEthDouble(balance_wei);
//Balance of Account B before transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, TEST_ETH_RECIPIENT_ADDR_0)), "Account B before the transfer" );
balance_bef_b = UtilityWeiStrToEthDouble(balance_wei);
//Account A transfers 0.01ETH to Account B
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_EthereumTransfer_0(g_case_10_ethereum_wallet_ptr), "Case_10_EthereumTransfer_0" );
//Balance of account A after transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, NULL)), "After account A is transferred" );
balance_aft_a = UtilityWeiStrToEthDouble(balance_wei);
//Balance of account B after transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, TEST_ETH_RECIPIENT_ADDR_0)), "After account B is transferred" );
balance_aft_b = UtilityWeiStrToEthDouble(balance_wei);
//Calculate the difference before and after the transfer
BoatDisplayTestResult( ((balance_bef_a - balance_aft_a + 0.0001) >= UtilityWeiStrToEthDouble(TEST_ETH_TRANSFER_ETH_0)),"Case_10_EthereumTransfer A balance" );
BoatDisplayTestResult( ((balance_aft_b - balance_bef_b + 0.0001) >= UtilityWeiStrToEthDouble(TEST_ETH_TRANSFER_ETH_0)),"Case_10_EthereumTransfer B balance" );
//Call the contract
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_Call_ReadStore_0(g_case_10_ethereum_wallet_ptr), "Case_10_Call_ReadStore_0" );
return BOAT_SUCCESS;
}
//test case 6:load wallet
BOAT_RESULT Case_10_EthereumPreCondition_6(BSINT8 *wallet_num)
{
BSINT32 index;
BoatEthWalletConfig wallet_config;
BoatEthWallet *wallet_ptr;
// Set Private Key
UtilityHex2Bin( wallet_config.priv_key_array,
32,
TEST_ETH_PRIVATE_KEY_0,
TRIMBIN_TRIM_NO,
BOAT_FALSE);
wallet_config.chain_id = 1;
wallet_config.eip155_compatibility = 0;
// Set Node URL
wallet_config.node_url_str[BOAT_NODE_URL_MAX_LEN-1] = '\0';
strncpy(wallet_config.node_url_str, TEST_ETH_NODE_URL_0, BOAT_NODE_URL_MAX_LEN-1);
// Load an existed wallet
index = BoatWalletCreate(TEST_ETH_PROTOCOL_0, TEST_ETH_WALLET_NAME_0, NULL, sizeof(BoatEthWalletConfig));
if( index == -1 )
{
BoatLog(BOAT_LOG_NORMAL, "Fail to create wallet.");
return BOAT_ERROR;
}
wallet_ptr = BoatGetWalletByIndex(index);
g_case_10_ethereum_wallet_ptr = wallet_ptr;
*wallet_num =index;
return BOAT_SUCCESS;
}
BOAT_RESULT Case_10_EthFunTest_6(BSINT8 *wallet_num)
{
BCHAR * balance_wei;
//A account
double balance_bef_a=0.0;
double balance_aft_a=0.0;
//B account
double balance_bef_b=0.0;
double balance_aft_b=0.0;
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_EthereumPreCondition_6(wallet_num), "[Case_10_EthFunTest_6]:PreCondition_6" );
//Balance of Account A before transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, NULL)), " Account A before the transfer" );
balance_bef_a = UtilityWeiStrToEthDouble(balance_wei);
//Balance of Account B before transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, TEST_ETH_RECIPIENT_ADDR_0)), "Account B before the transfer" );
balance_bef_b = UtilityWeiStrToEthDouble(balance_wei);
//Account A transfers 0.01ETH to Account B
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_EthereumTransfer_0(g_case_10_ethereum_wallet_ptr), "Case_10_EthereumTransfer_0" );
//Balance of account A after transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, NULL)), "After account A is transferred" );
balance_aft_a = UtilityWeiStrToEthDouble(balance_wei);
//Balance of account B after transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, TEST_ETH_RECIPIENT_ADDR_0)), "After account B is transferred " );
balance_aft_b = UtilityWeiStrToEthDouble(balance_wei);
//Calculate the difference before and after the transfer
BoatDisplayTestResult( ((balance_bef_a - balance_aft_a + 0.0001) >= UtilityWeiStrToEthDouble(TEST_ETH_TRANSFER_ETH_0))," A balance" );
BoatDisplayTestResult( ((balance_aft_b - balance_bef_b + 0.0001) >= UtilityWeiStrToEthDouble(TEST_ETH_TRANSFER_ETH_0))," B balance" );
//Call the contract
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_Call_ReadStore_0(g_case_10_ethereum_wallet_ptr), "Case_10_Call_ReadStore_0" );
return BOAT_SUCCESS;
}
//test case 7: one-time wallet
BOAT_RESULT Case_10_EthereumPreCondition_7(BSINT8 *wallet_num)
{
BSINT32 index;
BoatEthWalletConfig wallet_config;
BoatEthWallet *wallet_ptr;
// Set Private Key
UtilityHex2Bin( wallet_config.priv_key_array,
32,
TEST_ETH_PRIVATE_KEY_0,
TRIMBIN_TRIM_NO,
BOAT_FALSE);
wallet_config.chain_id = 1;
wallet_config.eip155_compatibility = 0;
// Set Node URL
wallet_config.node_url_str[BOAT_NODE_URL_MAX_LEN-1] = '\0';
strncpy(wallet_config.node_url_str, TEST_ETH_NODE_URL_0, BOAT_NODE_URL_MAX_LEN-1);
// Test one-time wallet
index = BoatWalletCreate(TEST_ETH_PROTOCOL_0, NULL, &wallet_config, sizeof(BoatEthWalletConfig));
if( index == -1 )
{
BoatLog(BOAT_LOG_NORMAL, "Fail to create wallet.");
return BOAT_ERROR;
}
wallet_ptr = BoatGetWalletByIndex(index);
g_case_10_ethereum_wallet_ptr = wallet_ptr;
*wallet_num = index;
return BOAT_SUCCESS;
}
BOAT_RESULT Case_10_EthFunTest_7(BSINT8 *wallet_num)
{
BCHAR * balance_wei;
//A account
double balance_bef_a=0.0;
double balance_aft_a=0.0;
//B account
double balance_bef_b=0.0;
double balance_aft_b=0.0;
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_EthereumPreCondition_7(wallet_num), "[Case_10_EthFunTest_7]:PreCondition_7" );
//Balance of Account A before transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, NULL)), "Account A before the transfer" );
balance_bef_a = UtilityWeiStrToEthDouble(balance_wei);
//Balance of Account B before transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, TEST_ETH_RECIPIENT_ADDR_0)), "Account B before the transfer" );
balance_bef_b = UtilityWeiStrToEthDouble(balance_wei);
//Account A transfers 0.01ETH to Account B
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_EthereumTransfer_0(g_case_10_ethereum_wallet_ptr), "Case_10_EthereumTransfer_0" );
//Balance of account A after transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, NULL)), "After account A is transferred" );
balance_aft_a = UtilityWeiStrToEthDouble(balance_wei);
//Balance of account B after transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, TEST_ETH_RECIPIENT_ADDR_0)), "After account B is transferred" );
balance_aft_b = UtilityWeiStrToEthDouble(balance_wei);
//Calculate the difference before and after the transfer
BoatDisplayTestResult( ((balance_bef_a - balance_aft_a + 0.0001) >= UtilityWeiStrToEthDouble(TEST_ETH_TRANSFER_ETH_0)),"Case_10_EthereumTransfer A balance" );
BoatDisplayTestResult( ((balance_aft_b - balance_bef_b + 0.0001) >= UtilityWeiStrToEthDouble(TEST_ETH_TRANSFER_ETH_0)),"Case_10_EthereumTransfer B balance" );
//Call the contract
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_Call_ReadStore_0(g_case_10_ethereum_wallet_ptr), "Case_10_Call_ReadStore_0" );
return BOAT_SUCCESS;
}
//test case 8: wallet name path error
BOAT_RESULT Case_10_EthereumPreCondition_8(BSINT8 *wallet_num)
{
BSINT32 index;
BoatEthWalletConfig wallet_config;
BoatEthWallet *wallet_ptr;
// Set Private Key
UtilityHex2Bin( wallet_config.priv_key_array,
32,
TEST_ETH_PRIVATE_KEY_0,
TRIMBIN_TRIM_NO,
BOAT_FALSE);
wallet_config.chain_id = 1;
wallet_config.eip155_compatibility = 0;
// Set Node URL
wallet_config.node_url_str[BOAT_NODE_URL_MAX_LEN-1] = '\0';
strncpy(wallet_config.node_url_str, TEST_ETH_NODE_URL_0, BOAT_NODE_URL_MAX_LEN-1);
// Create a new wallet or overwrite an existed wallet
index = BoatWalletCreate(TEST_ETH_PROTOCOL_0, TEST_ETH_WALLET_NAME_1, &wallet_config, sizeof(BoatEthWalletConfig));
if( index == -1 )
{
BoatLog(BOAT_LOG_NORMAL, "Fail to create wallet.");
return BOAT_ERROR;
}
wallet_ptr = BoatGetWalletByIndex(index);
g_case_10_ethereum_wallet_ptr = wallet_ptr;
*wallet_num = index;
return BOAT_SUCCESS;
}
BOAT_RESULT Case_10_EthFunTest_8(BSINT8 *wallet_num)
{
BCHAR * balance_wei;
//A account
double balance_bef_a=0.0;
double balance_aft_a=0.0;
//B account
double balance_bef_b=0.0;
double balance_aft_b=0.0;
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_EthereumPreCondition_8(wallet_num), "[Case_10_EthFunTest_8]:PreCondition_8" );
//Balance of Account A before transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, NULL)), "Account A before the transfer" );
balance_bef_a = UtilityWeiStrToEthDouble(balance_wei);
//Balance of Account B before transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, TEST_ETH_RECIPIENT_ADDR_0)), "Account B before the transfer" );
balance_bef_b = UtilityWeiStrToEthDouble(balance_wei);
//Account A transfers 0.01ETH to Account B
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_EthereumTransfer_0(g_case_10_ethereum_wallet_ptr), "Case_10_EthereumTransfer_0" );
//Balance of account A after transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, NULL)), "After account A is transferred" );
balance_aft_a = UtilityWeiStrToEthDouble(balance_wei);
//Balance of account B after transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, TEST_ETH_RECIPIENT_ADDR_0)), "After account B is transferred" );
balance_aft_b = UtilityWeiStrToEthDouble(balance_wei);
//Calculate the difference before and after the transfer
BoatDisplayTestResult( ((balance_bef_a - balance_aft_a + 0.0001) >= UtilityWeiStrToEthDouble(TEST_ETH_TRANSFER_ETH_0)),"Case_10_EthereumTransfer A balance" );
BoatDisplayTestResult( ((balance_aft_b - balance_bef_b + 0.0001) >= UtilityWeiStrToEthDouble(TEST_ETH_TRANSFER_ETH_0)),"Case_10_EthereumTransfer B balance" );
//Call the contract
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_Call_ReadStore_0(g_case_10_ethereum_wallet_ptr), "Case_10_Call_ReadStore_0" );
return BOAT_SUCCESS;
}
//test case 9: is_sync_tx=BOAT_FALSE
BOAT_RESULT Case_10_EthereumTransfer_9(BoatEthWallet *wallet_ptr)
{
BoatEthTx tx_ctx;
// Set Recipient Address
BoatDisplayTestResult(BOAT_SUCCESS == BoatEthTxInit(wallet_ptr,&tx_ctx,BOAT_FALSE,TEST_ETH_GASPRICE_0,TEST_ETH_GASLIMIT_0,TEST_ETH_RECIPIENT_ADDR_0),"BoatEthTxInit");
BoatDisplayTestResult(BOAT_SUCCESS == BoatEthTransfer(&tx_ctx, TEST_ETH_TRANSFER_ETH_0),"BoatEthTransfer");
return BOAT_SUCCESS;
}
BOAT_RESULT Case_10_EthFunTest_9(BSINT8 *wallet_num)
{
BCHAR * balance_wei;
//A account
double balance_bef_a=0.0;
double balance_aft_a=0.0;
//B account
double balance_bef_b=0.0;
double balance_aft_b=0.0;
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_EthereumPreCondition_0(wallet_num), "[Case_10_EthFunTest_9]:PreCondition_0" );
//Balance of Account A before transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, NULL)), "Account A before the transfer" );
balance_bef_a = UtilityWeiStrToEthDouble(balance_wei);
//Balance of Account B before transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, TEST_ETH_RECIPIENT_ADDR_0)), "Account B before the transfer" );
balance_bef_b = UtilityWeiStrToEthDouble(balance_wei);
//Account A transfers 0.01ETH to Account B
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_EthereumTransfer_0(g_case_10_ethereum_wallet_ptr), "Case_10_EthereumTransfer_0" );
//Balance of account A after transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, NULL)), "After account A is transferred" );
balance_aft_a = UtilityWeiStrToEthDouble(balance_wei);
//Balance of account B after transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, TEST_ETH_RECIPIENT_ADDR_0)), "After account B is transferred" );
balance_aft_b = UtilityWeiStrToEthDouble(balance_wei);
//Calculate the difference before and after the transfer
BoatDisplayTestResult( ((balance_bef_a - balance_aft_a + 0.0001) >= UtilityWeiStrToEthDouble(TEST_ETH_TRANSFER_ETH_0)),"Case_10_EthereumTransfer A balance" );
BoatDisplayTestResult( ((balance_aft_b - balance_bef_b + 0.0001) >= UtilityWeiStrToEthDouble(TEST_ETH_TRANSFER_ETH_0)),"Case_10_EthereumTransfer B balance" );
return BOAT_SUCCESS;
}
//test case 10: TEST_ETH_GASPRICE_1
BOAT_RESULT Case_10_EthereumTransfer_10(BoatEthWallet *wallet_ptr)
{
BoatEthTx tx_ctx;
// Set Recipient Address
BoatDisplayTestResult(BOAT_SUCCESS == BoatEthTxInit(wallet_ptr,&tx_ctx,BOAT_TRUE,TEST_ETH_GASPRICE_1,TEST_ETH_GASLIMIT_0,TEST_ETH_RECIPIENT_ADDR_0),"BoatEthTxInit");
BoatDisplayTestResult(BOAT_SUCCESS == BoatEthTransfer(&tx_ctx, TEST_ETH_TRANSFER_ETH_0),"BoatEthTransfer");
return BOAT_SUCCESS;
}
BOAT_RESULT Case_10_EthFunTest_10(BSINT8 *wallet_num)
{
BCHAR * balance_wei;
//A account
double balance_bef_a=0.0;
double balance_aft_a=0.0;
//B account
double balance_bef_b=0.0;
double balance_aft_b=0.0;
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_EthereumPreCondition_0(wallet_num), "[Case_10_EthFunTest_10]:PreCondition_0" );
//Balance of Account A before transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, NULL)), "Account A before the transfer" );
balance_bef_a = UtilityWeiStrToEthDouble(balance_wei);
//Balance of Account B before transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, TEST_ETH_RECIPIENT_ADDR_0)), "Account B before the transfer" );
balance_bef_b = UtilityWeiStrToEthDouble(balance_wei);
//Account A transfers 0.01ETH to Account B
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_EthereumTransfer_0(g_case_10_ethereum_wallet_ptr), "Case_10_EthereumTransfer_0" );
//Balance of account A after transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, NULL)), "After account A is transferred" );
balance_aft_a = UtilityWeiStrToEthDouble(balance_wei);
//Balance of account B after transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, TEST_ETH_RECIPIENT_ADDR_0)), "After account B is transferred" );
balance_aft_b = UtilityWeiStrToEthDouble(balance_wei);
//Calculate the difference before and after the transfer
BoatDisplayTestResult( ((balance_bef_a - balance_aft_a + 0.0001) >= UtilityWeiStrToEthDouble(TEST_ETH_TRANSFER_ETH_0)),"Case_10_EthereumTransfer A balance" );
BoatDisplayTestResult( ((balance_aft_b - balance_bef_b + 0.0001) >= UtilityWeiStrToEthDouble(TEST_ETH_TRANSFER_ETH_0)),"Case_10_EthereumTransfer B balance" );
return BOAT_SUCCESS;
}
//test case 11: TEST_ETH_GASLIMIT_1
BOAT_RESULT Case_10_EthereumTransfer_11(BoatEthWallet *wallet_ptr)
{
BoatEthTx tx_ctx;
// Set Recipient Address
BoatDisplayTestResult(BOAT_SUCCESS == BoatEthTxInit(wallet_ptr,&tx_ctx,BOAT_TRUE,TEST_ETH_GASPRICE_0,TEST_ETH_GASLIMIT_1,TEST_ETH_RECIPIENT_ADDR_0),"BoatEthTxInit");
BoatDisplayTestResult(BOAT_SUCCESS == BoatEthTransfer(&tx_ctx, TEST_ETH_TRANSFER_ETH_0),"BoatEthTransfer");
return BOAT_SUCCESS;
}
BOAT_RESULT Case_10_EthFunTest_11(BSINT8 *wallet_num)
{
BCHAR * balance_wei;
//A account
double balance_bef_a=0.0;
double balance_aft_a=0.0;
//B account
double balance_bef_b=0.0;
double balance_aft_b=0.0;
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_EthereumPreCondition_0(wallet_num), "[Case_10_EthFunTest_11]:PreCondition_0" );
//Balance of Account A before transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, NULL)), "Account A before the transfer" );
balance_bef_a = UtilityWeiStrToEthDouble(balance_wei);
//Balance of Account B before transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, TEST_ETH_RECIPIENT_ADDR_0)), "Account B before the transfer" );
balance_bef_b = UtilityWeiStrToEthDouble(balance_wei);
//Account A transfers 0.01ETH to Account B
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_EthereumTransfer_0(g_case_10_ethereum_wallet_ptr), "Case_10_EthereumTransfer_0" );
//Balance of account A after transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, NULL)), "After account A is transferred" );
balance_aft_a = UtilityWeiStrToEthDouble(balance_wei);
//Balance of account B after transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, TEST_ETH_RECIPIENT_ADDR_0)), "After account B is transferred" );
balance_aft_b = UtilityWeiStrToEthDouble(balance_wei);
//Calculate the difference before and after the transfer
BoatDisplayTestResult( ((balance_bef_a - balance_aft_a + 0.0001) >= UtilityWeiStrToEthDouble(TEST_ETH_TRANSFER_ETH_0)),"Case_10_EthereumTransfer A balance" );
BoatDisplayTestResult( ((balance_aft_b - balance_bef_b + 0.0001) >= UtilityWeiStrToEthDouble(TEST_ETH_TRANSFER_ETH_0)),"Case_10_EthereumTransfer B balance" );
return BOAT_SUCCESS;
}
//test case 12: TEST_ETH_RECIPIENT_ADDR_1
BOAT_RESULT Case_10_EthereumTransfer_12(BoatEthWallet *wallet_ptr)
{
BoatEthTx tx_ctx;
// Set Recipient Address
BoatDisplayTestResult(BOAT_SUCCESS == BoatEthTxInit(wallet_ptr,&tx_ctx,BOAT_TRUE,TEST_ETH_GASPRICE_0,TEST_ETH_GASLIMIT_0,TEST_ETH_RECIPIENT_ADDR_1),"BoatEthTxInit");
BoatDisplayTestResult(BOAT_SUCCESS == BoatEthTransfer(&tx_ctx, TEST_ETH_TRANSFER_ETH_0),"BoatEthTransfer");
return BOAT_SUCCESS;
}
BOAT_RESULT Case_10_EthFunTest_12(BSINT8 *wallet_num)
{
BCHAR * balance_wei;
//A account
double balance_bef_a=0.0;
double balance_aft_a=0.0;
//B account
double balance_bef_b=0.0;
double balance_aft_b=0.0;
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_EthereumPreCondition_0(wallet_num), "[Case_10_EthFunTest_12]:PreCondition_0" );
//Balance of Account A before transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, NULL)), "Account A before the transfer" );
balance_bef_a = UtilityWeiStrToEthDouble(balance_wei);
//Balance of Account B before transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, TEST_ETH_RECIPIENT_ADDR_0)), "Account B before the transfer" );
balance_bef_b = UtilityWeiStrToEthDouble(balance_wei);
//Account A transfers 0.01ETH to Account B
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_EthereumTransfer_0(g_case_10_ethereum_wallet_ptr), "Case_10_EthereumTransfer_0" );
//Balance of account A after transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, NULL)), "After account A is transferred" );
balance_aft_a = UtilityWeiStrToEthDouble(balance_wei);
//Balance of account B after transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, TEST_ETH_RECIPIENT_ADDR_0)), "After account B is transferred" );
balance_aft_b = UtilityWeiStrToEthDouble(balance_wei);
//Calculate the difference before and after the transfer
BoatDisplayTestResult( ((balance_bef_a - balance_aft_a + 0.0001) >= UtilityWeiStrToEthDouble(TEST_ETH_TRANSFER_ETH_0)),"Case_10_EthereumTransfer A balance" );
BoatDisplayTestResult( ((balance_aft_b - balance_bef_b + 0.0001) >= UtilityWeiStrToEthDouble(TEST_ETH_TRANSFER_ETH_0)),"Case_10_EthereumTransfer B balance" );
return BOAT_SUCCESS;
}
//test case 13: TEST_ETH_TRANSFER_ETH_1
BOAT_RESULT Case_10_EthereumTransfer_13(BoatEthWallet *wallet_ptr)
{
BoatEthTx tx_ctx;
// Set Recipient Address
BoatDisplayTestResult(BOAT_SUCCESS == BoatEthTxInit(wallet_ptr,&tx_ctx,BOAT_TRUE,TEST_ETH_GASPRICE_0,TEST_ETH_GASLIMIT_0,TEST_ETH_RECIPIENT_ADDR_0),"BoatEthTxInit");
BoatDisplayTestResult(BOAT_SUCCESS == BoatEthTransfer(&tx_ctx, TEST_ETH_TRANSFER_ETH_1),"[EthereumTransfer_13]:BoatEthTransfer");
return BOAT_SUCCESS;
}
BOAT_RESULT Case_10_EthFunTest_13(BSINT8 *wallet_num)
{
BCHAR * balance_wei;
//A account
double balance_bef_a=0.0;
double balance_aft_a=0.0;
//B account
double balance_bef_b=0.0;
double balance_aft_b=0.0;
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_EthereumPreCondition_0(wallet_num), "[Case_10_EthFunTest_13]:PreCondition_0" );
//Balance of Account A before transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, NULL)), "Account A before the transfer" );
balance_bef_a = UtilityWeiStrToEthDouble(balance_wei);
printf("balance_bef_a:%lf\n",balance_bef_a);
//Balance of Account B before transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, TEST_ETH_RECIPIENT_ADDR_0)), "Account B before the transfer" );
balance_bef_b = UtilityWeiStrToEthDouble(balance_wei);
//Account A transfers 0.01ETH to Account B
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_EthereumTransfer_13(g_case_10_ethereum_wallet_ptr), "Case_10_EthereumTransfer_0" );
//Balance of account A after transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, NULL)), "After account A is transferred" );
balance_aft_a = UtilityWeiStrToEthDouble(balance_wei);
printf("balance_aft_a:%lf\n",balance_aft_a);
//Balance of account B after transfer
BoatDisplayTestResult( NULL != (balance_wei = BoatEthWalletGetBalance(g_case_10_ethereum_wallet_ptr, TEST_ETH_RECIPIENT_ADDR_0)), "After account B is transferred" );
balance_aft_b = UtilityWeiStrToEthDouble(balance_wei);
//Calculate the difference before and after the transfer
BoatDisplayTestResult( ((balance_bef_a - balance_aft_a + 0.0001) >= UtilityWeiStrToEthDouble(TEST_ETH_TRANSFER_ETH_1)),"Case_10_EthereumTransfer A balance" );
BoatDisplayTestResult( ((balance_aft_b - balance_bef_b + 0.0001) >= UtilityWeiStrToEthDouble(TEST_ETH_TRANSFER_ETH_1)),"Case_10_EthereumTransfer B balance" );
return BOAT_SUCCESS;
}
//test case 14: newevent = 64
BOAT_RESULT Case_10_Call_ReadStore_14(BoatEthWallet *wallet_ptr)
{
BCHAR *result_str;
BUINT32 list_len;
BUINT32 index_u256_big[32/4];
BUINT8 result_buff[127];
BUINT32 index;
BoatEthTx tx_ctx;
// Set Contract Address
BoatDisplayTestResult(BOAT_SUCCESS == BoatEthTxInit(wallet_ptr,&tx_ctx,BOAT_TRUE,TEST_ETH_GASPRICE_0,TEST_ETH_GASLIMIT_0,TEST_ETH_CONTRACT_ADDR_0),"BoatEthTxInit");
BoatDisplayTestResult(NULL != (result_str = StoreRead_saveList(&tx_ctx, (BUINT8 *)"64")),"StoreRead_saveList");
BoatLog(BOAT_LOG_NORMAL, "StoreRead_saveList returns: %s", result_str);
BoatDisplayTestResult(NULL != (result_str = StoreRead_readListLength(&tx_ctx)),"StoreRead_readListLength");
BoatLog(BOAT_LOG_NORMAL, "readListLength returns: %s", result_str);
UtilityHex2Bin((BUINT8*)index_u256_big,sizeof(index_u256_big),result_str,TRIMBIN_TRIM_NO,BOAT_FALSE);
UtilityChangeEndian(index_u256_big, sizeof(index_u256_big));
list_len = index_u256_big[0];
index = list_len-1;
BoatDisplayTestResult(NULL != (result_str = StoreRead_readListByIndex(&tx_ctx, index)),"StoreRead_readListByIndex");
BoatLog(BOAT_LOG_NORMAL, "StoreRead_readListByIndex returns: %s\n", result_str);
UtilityHex2Bin(result_buff,sizeof(result_buff),result_str,TRIMBIN_TRIM_NO, BOAT_FALSE);
BoatDisplayTestResult( 0 == memcmp(result_buff,"64",strlen("64")), "readListByIndex-memcmp" );
return BOAT_SUCCESS;
}
BOAT_RESULT Case_10_EthFunTest_14(BSINT8 *wallet_num)
{
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_EthereumPreCondition_0(wallet_num), "[Case_10_EthFunTest_14]:PreCondition_0" );
//Call the contract
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_Call_ReadStore_14(g_case_10_ethereum_wallet_ptr), "[Case_10_EthFunTest_14]:Case_10_Call_ReadStore_14" );
return BOAT_SUCCESS;
}
//test case 15: is_sync_tx = BOAT_FALSE
BOAT_RESULT Case_10_Call_ReadStore_15(BoatEthWallet *wallet_ptr)
{
BCHAR *result_str;
BUINT32 list_len;
BUINT32 index_u256_big[32/4];
BUINT8 result_buff[127];
BUINT32 index;
BoatEthTx tx_ctx;
// Set Contract Address
BoatDisplayTestResult(BOAT_SUCCESS == BoatEthTxInit(wallet_ptr,&tx_ctx,BOAT_FALSE,TEST_ETH_GASPRICE_0,TEST_ETH_GASLIMIT_0,TEST_ETH_CONTRACT_ADDR_0),"BoatEthTxInit");
BoatDisplayTestResult(NULL != (result_str = StoreRead_saveList(&tx_ctx, (BUINT8 *)"hello world")),"StoreRead_saveList");
BoatLog(BOAT_LOG_NORMAL, "StoreRead_saveList returns: %s", result_str);
BoatDisplayTestResult(NULL != (result_str = StoreRead_readListLength(&tx_ctx)),"StoreRead_readListLength");
BoatLog(BOAT_LOG_NORMAL, "readListLength returns: %s", result_str);
UtilityHex2Bin((BUINT8*)index_u256_big,sizeof(index_u256_big),result_str,TRIMBIN_TRIM_NO,BOAT_FALSE);
UtilityChangeEndian(index_u256_big, sizeof(index_u256_big));
list_len = index_u256_big[0];
index = list_len-1;
BoatDisplayTestResult(NULL != (result_str = StoreRead_readListByIndex(&tx_ctx, index)),"StoreRead_readListByIndex");
BoatLog(BOAT_LOG_NORMAL, "StoreRead_readListByIndex returns: %s\n", result_str);
UtilityHex2Bin(result_buff,sizeof(result_buff),result_str,TRIMBIN_TRIM_NO, BOAT_FALSE);
BoatDisplayTestResult( 0 == memcmp(result_buff,"Hello world",strlen("Hello world")), "readListByIndex-memcmp" );
return BOAT_SUCCESS;
}
BOAT_RESULT Case_10_EthFunTest_15(BSINT8 *wallet_num)
{
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_EthereumPreCondition_0(wallet_num), "[Case_10_EthFunTest_15]:PreCondition_0" );
//Call the contract
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_Call_ReadStore_0(g_case_10_ethereum_wallet_ptr), "Case_10_Call_ReadStore_0" );
return BOAT_SUCCESS;
}
//test case 16: TEST_ETH_GASPRICE_1
BOAT_RESULT Case_10_Call_ReadStore_16(BoatEthWallet *wallet_ptr)
{
BCHAR *result_str;
BUINT32 list_len;
BUINT32 index_u256_big[32/4];
BUINT8 result_buff[127];
BUINT32 index;
BoatEthTx tx_ctx;
// Set Contract Address
BoatDisplayTestResult(BOAT_SUCCESS == BoatEthTxInit(wallet_ptr,&tx_ctx,BOAT_TRUE,TEST_ETH_GASPRICE_1,TEST_ETH_GASLIMIT_0,TEST_ETH_CONTRACT_ADDR_0),"BoatEthTxInit");
BoatDisplayTestResult(NULL != (result_str = StoreRead_saveList(&tx_ctx, (BUINT8 *)"hello world")),"StoreRead_saveList");
BoatLog(BOAT_LOG_NORMAL, "StoreRead_saveList returns: %s", result_str);
BoatDisplayTestResult(NULL != (result_str = StoreRead_readListLength(&tx_ctx)),"StoreRead_readListLength");
BoatLog(BOAT_LOG_NORMAL, "readListLength returns: %s", result_str);
UtilityHex2Bin((BUINT8*)index_u256_big,sizeof(index_u256_big),result_str,TRIMBIN_TRIM_NO,BOAT_FALSE);
UtilityChangeEndian(index_u256_big, sizeof(index_u256_big));
list_len = index_u256_big[0];
index = list_len-1;
BoatDisplayTestResult(NULL != (result_str = StoreRead_readListByIndex(&tx_ctx, index)),"StoreRead_readListByIndex");
BoatLog(BOAT_LOG_NORMAL, "StoreRead_readListByIndex returns: %s\n", result_str);
UtilityHex2Bin(result_buff,sizeof(result_buff),result_str,TRIMBIN_TRIM_NO, BOAT_FALSE);
BoatDisplayTestResult( 0 == memcmp(result_buff,"Hello world",strlen("Hello world")), "readListByIndex-memcmp" );
return BOAT_SUCCESS;
}
BOAT_RESULT Case_10_EthFunTest_16(BSINT8 *wallet_num)
{
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_EthereumPreCondition_0(wallet_num), "[Case_10_EthFunTest_16]:PreCondition_0" );
//Call the contract
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_Call_ReadStore_0(g_case_10_ethereum_wallet_ptr), "Case_10_Call_ReadStore_0" );
return BOAT_SUCCESS;
}
//test case 17: TEST_ETH_GASLIMIT_1
BOAT_RESULT Case_10_Call_ReadStore_17(BoatEthWallet *wallet_ptr)
{
BCHAR *result_str;
BUINT32 list_len;
BUINT32 index_u256_big[32/4];
BUINT8 result_buff[127];
BUINT32 index;
BoatEthTx tx_ctx;
// Set Contract Address
BoatDisplayTestResult(BOAT_SUCCESS == BoatEthTxInit(wallet_ptr,&tx_ctx,BOAT_TRUE,TEST_ETH_GASPRICE_0,TEST_ETH_GASLIMIT_1,TEST_ETH_CONTRACT_ADDR_0),"BoatEthTxInit");
BoatDisplayTestResult(NULL != (result_str = StoreRead_saveList(&tx_ctx, (BUINT8 *)"hello world")),"StoreRead_saveList");
BoatLog(BOAT_LOG_NORMAL, "StoreRead_saveList returns: %s", result_str);
BoatDisplayTestResult(NULL != (result_str = StoreRead_readListLength(&tx_ctx)),"StoreRead_readListLength");
BoatLog(BOAT_LOG_NORMAL, "readListLength returns: %s", result_str);
UtilityHex2Bin((BUINT8*)index_u256_big,sizeof(index_u256_big),result_str,TRIMBIN_TRIM_NO,BOAT_FALSE);
UtilityChangeEndian(index_u256_big, sizeof(index_u256_big));
list_len = index_u256_big[0];
index = list_len-1;
BoatDisplayTestResult(NULL != (result_str = StoreRead_readListByIndex(&tx_ctx, index)),"StoreRead_readListByIndex");
BoatLog(BOAT_LOG_NORMAL, "StoreRead_readListByIndex returns: %s\n", result_str);
UtilityHex2Bin(result_buff,sizeof(result_buff),result_str,TRIMBIN_TRIM_NO, BOAT_FALSE);
BoatDisplayTestResult( 0 == memcmp(result_buff,"Hello world",strlen("Hello world")), "readListByIndex-memcmp" );
return BOAT_SUCCESS;
}
BOAT_RESULT Case_10_EthFunTest_17(BSINT8 *wallet_num)
{
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_EthereumPreCondition_0(wallet_num), "[Case_10_EthFunTest_17]:PreCondition_0" );
//Call the contract
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_Call_ReadStore_0(g_case_10_ethereum_wallet_ptr), "Case_10_Call_ReadStore_0" );
return BOAT_SUCCESS;
}
//test case 18: TEST_ETH_GASLIMIT_2
BOAT_RESULT Case_10_Call_ReadStore_18(BoatEthWallet *wallet_ptr)
{
BCHAR *result_str;
BUINT32 list_len;
BUINT32 index_u256_big[32/4];
BUINT8 result_buff[127];
BUINT32 index;
BoatEthTx tx_ctx;
// Set Contract Address
BoatDisplayTestResult(BOAT_SUCCESS == BoatEthTxInit(wallet_ptr,&tx_ctx,BOAT_TRUE,TEST_ETH_GASPRICE_0,TEST_ETH_GASLIMIT_2,TEST_ETH_CONTRACT_ADDR_0),"[ReadStore_18]:BoatEthTxInit");
BoatDisplayTestResult(NULL != (result_str = StoreRead_saveList(&tx_ctx, (BUINT8 *)"hello world")),"[ReadStore_18]:StoreRead_saveList");
BoatLog(BOAT_LOG_NORMAL, "StoreRead_saveList returns: %s", result_str);
BoatDisplayTestResult(NULL != (result_str = StoreRead_readListLength(&tx_ctx)),"[ReadStore_18]:StoreRead_readListLength");
BoatLog(BOAT_LOG_NORMAL, "readListLength returns: %s", result_str);
UtilityHex2Bin((BUINT8*)index_u256_big,sizeof(index_u256_big),result_str,TRIMBIN_TRIM_NO,BOAT_FALSE);
UtilityChangeEndian(index_u256_big, sizeof(index_u256_big));
list_len = index_u256_big[0];
index = list_len-1;
BoatDisplayTestResult(NULL != (result_str = StoreRead_readListByIndex(&tx_ctx, index)),"[ReadStore_18]:StoreRead_readListByIndex");
BoatLog(BOAT_LOG_NORMAL, "StoreRead_readListByIndex returns: %s\n", result_str);
UtilityHex2Bin(result_buff,sizeof(result_buff),result_str,TRIMBIN_TRIM_NO, BOAT_FALSE);
BoatDisplayTestResult( 0 != memcmp(result_buff,"Hello world",strlen("Hello world")), "[ReadStore_18]:readListByIndex-memcmp" );
return BOAT_SUCCESS;
}
BOAT_RESULT Case_10_EthFunTest_18(BSINT8 *wallet_num)
{
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_EthereumPreCondition_0(wallet_num), "[Case_10_EthFunTest_18]:PreCondition_0" );
//Call the contract
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_Call_ReadStore_18(g_case_10_ethereum_wallet_ptr), "[Case_10_EthFunTest_18]:ReadStore_18" );
return BOAT_SUCCESS;
}
//test case 19: TEST_ETH_CONTRACT_ADDR_1
BOAT_RESULT Case_10_Call_ReadStore_19(BoatEthWallet *wallet_ptr)
{
BCHAR *result_str;
BUINT32 list_len;
BUINT32 index_u256_big[32/4];
BUINT8 result_buff[127];
BUINT32 index;
BoatEthTx tx_ctx;
// Set Contract Address
BoatDisplayTestResult(BOAT_SUCCESS == BoatEthTxInit(wallet_ptr,&tx_ctx,BOAT_TRUE,TEST_ETH_GASPRICE_0,TEST_ETH_GASLIMIT_0,TEST_ETH_CONTRACT_ADDR_1),"[ReadStore_19]:BoatEthTxInit");
BoatDisplayTestResult(NULL != (result_str = StoreRead_saveList(&tx_ctx, (BUINT8 *)"hello world")),"[ReadStore_19]:StoreRead_saveList");
BoatLog(BOAT_LOG_NORMAL, "StoreRead_saveList returns: %s", result_str);
BoatDisplayTestResult(NULL != (result_str = StoreRead_readListLength(&tx_ctx)),"[ReadStore_19]:StoreRead_readListLength");
BoatLog(BOAT_LOG_NORMAL, "readListLength returns: %s", result_str);
UtilityHex2Bin((BUINT8*)index_u256_big,sizeof(index_u256_big),result_str,TRIMBIN_TRIM_NO,BOAT_FALSE);
UtilityChangeEndian(index_u256_big, sizeof(index_u256_big));
list_len = index_u256_big[0];
index = list_len-1;
BoatDisplayTestResult(NULL != (result_str = StoreRead_readListByIndex(&tx_ctx, index)),"[ReadStore_19]:StoreRead_readListByIndex");
BoatLog(BOAT_LOG_NORMAL, "StoreRead_readListByIndex returns: %s\n", result_str);
UtilityHex2Bin(result_buff,sizeof(result_buff),result_str,TRIMBIN_TRIM_NO, BOAT_FALSE);
BoatDisplayTestResult( 0 != memcmp(result_buff,"Hello world",strlen("Hello world")), "[ReadStore_19]:readListByIndex-memcmp" );
return BOAT_SUCCESS;
}
BOAT_RESULT Case_10_EthFunTest_19(BSINT8 *wallet_num)
{
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_EthereumPreCondition_0(wallet_num), "[Case_10_EthFunTest_19]:PreCondition_0" );
//Call the contract
BoatDisplayTestResult( BOAT_SUCCESS == Case_10_Call_ReadStore_19(g_case_10_ethereum_wallet_ptr), "[Case_10_EthFunTest_19]:ReadStore_19" );
return BOAT_SUCCESS;
}
/*****************************************************************************************************************************************************************/
BOAT_RESULT Case_10_EthFunMain(void)
{
BOAT_RESULT case_result = BOAT_SUCCESS;
BSINT8 wallet_num;
case_result += Case_10_EthFunTest_0(&wallet_num);
BoatWalletUnload(wallet_num);
//Condition
case_result += Case_10_EthFunTest_1(&wallet_num);
BoatWalletUnload(wallet_num);
case_result += Case_10_EthFunTest_2(&wallet_num);
BoatWalletUnload(wallet_num);
case_result += Case_10_EthFunTest_3(&wallet_num);
BoatWalletUnload(wallet_num);
case_result += Case_10_EthFunTest_4(&wallet_num);
BoatWalletUnload(wallet_num);
case_result += Case_10_EthFunTest_5(&wallet_num);
BoatWalletUnload(wallet_num);
case_result += Case_10_EthFunTest_6(&wallet_num);
BoatWalletUnload(wallet_num);
case_result += Case_10_EthFunTest_7(&wallet_num);
BoatWalletUnload(wallet_num);
case_result += Case_10_EthFunTest_8(&wallet_num);
BoatWalletUnload(wallet_num);
//Transfer
case_result += Case_10_EthFunTest_9(&wallet_num);
BoatWalletUnload(wallet_num);
case_result += Case_10_EthFunTest_10(&wallet_num);
BoatWalletUnload(wallet_num);
case_result += Case_10_EthFunTest_11(&wallet_num);
BoatWalletUnload(wallet_num);
case_result += Case_10_EthFunTest_12(&wallet_num);
BoatWalletUnload(wallet_num);
case_result += Case_10_EthFunTest_13(&wallet_num);
BoatWalletUnload(wallet_num);
//Contract
case_result += Case_10_EthFunTest_14(&wallet_num);
BoatWalletUnload(wallet_num);
case_result += Case_10_EthFunTest_15(&wallet_num);
BoatWalletUnload(wallet_num);
case_result += Case_10_EthFunTest_16(&wallet_num);
BoatWalletUnload(wallet_num);
case_result += Case_10_EthFunTest_17(&wallet_num);
BoatWalletUnload(wallet_num);
case_result += Case_10_EthFunTest_18(&wallet_num);
BoatWalletUnload(wallet_num);
case_result += Case_10_EthFunTest_19(&wallet_num);
BoatWalletUnload(wallet_num);
BoatLog(BOAT_LOG_NORMAL, "case_result:%d.\n", case_result);
//Delete wallet
BoatWalletDelete(TEST_ETH_WALLET_NAME_0);
return case_result;
}
|
gitter-badger/BoAT-X-Framework | sdk/protocol/boatprotocols.h | <filename>sdk/protocol/boatprotocols.h<gh_stars>1-10
/******************************************************************************
* Copyright (C) 2018-2021 aitos.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/*!@brief Header file wrapper for protocols
@file
boatprotocols.h is a wrapper header file for protocols.
*/
#ifndef __BOATPROTOCOLS_H__
#define __BOATPROTOCOLS_H__
#if PROTOCOL_USE_ETHEREUM
#include "boatethereum.h"
#endif
#if PROTOCOL_USE_HLFABRIC
#include "boathlfabric.h"
#endif
#if PROTOCOL_USE_PLATONE
#include "boatplatone.h"
#endif
#endif
|
gitter-badger/BoAT-X-Framework | hwdep/default/storage/persiststore.h | <gh_stars>1-10
/******************************************************************************
* Copyright (C) 2018-2020 aitos.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/*!@brief Default Persistent Storage Header File
@file
persiststore.h contains APIs declaration for default persistent storage as a file.
*/
#ifndef __PERSISTSTORE_H__
#define __PERSISTSTORE_H__
#include "boatinternal.h"
#ifdef __cplusplus
extern "C" {
#endif
BOAT_RESULT BoatPersistStore(const BCHAR *storage_name_str, const void *data_ptr, BUINT32 data_len);
BOAT_RESULT BoatPersistRead(const BCHAR *storage_name_str, BOAT_OUT void *data_ptr, BUINT32 len_to_read);
BOAT_RESULT BoatPersistDelete(const BCHAR * storage_name_str);
#ifdef __cplusplus
}
#endif /* end of __cplusplus */
#endif
|
gitter-badger/BoAT-X-Framework | hwdep/default/storage/persiststore.c | /******************************************************************************
* Copyright (C) 2018-2020 aitos.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/*!@brief Default Persistent Storage
@file
persiststore.c contains APIs for default persistent storage as a file.
*/
#include "boatinternal.h"
#include "randgenerator.h"
#include "sha3.h"
#if BOAT_USE_OPENSSL != 0
#include <openssl/evp.h>
#include <openssl/aes.h>
#endif
//!@brief Salt size for keystore
#define BOAT_STORAGE_SALT_SIZE 16
// AES KEY FOR DEVELOPMENT ONLY. DO NOT USE IT FOR PRODUCTION.
// Either replace it with a production key or replace the persitent storage
// mechanism with a secure one.
__BOATSTATIC const BUINT8 g_aes_key[32] = { 0x7F ,0x78, 0xBC, 0xEC, 0xD8, 0xBA, 0x96, 0xF7,
0x8E, 0x66, 0xFD, 0x98, 0xEA, 0x4A, 0x4E, 0x88,
0x0C, 0xB7, 0x34, 0xD3, 0x11, 0x9F, 0x72, 0xE0,
0x81, 0xD2, 0x5E, 0xC6, 0x16, 0xAC, 0x08, 0xC4};
/******************************************************************************
@brief AES encryption wrapper
Function: KeystoreEncrypt()
This function encrypts the data with AES-256 CBC.
In case OpenSSL is not availble, it simply encodes the data in a compatible
format without actual encryption.
It's for internally use only.
@see KeystoreDecrypt()
@return
This function returns BOAT_SUCCESS if it successfully encrypts the data.\n
Otherwise it returns one of the error codes.
@param[out] encrypted_ptr
Output buffer of the encrypted data.
@param[inout] encrypted_len_ptr
In: The size of <encrypted_ptr>.\n
Out: The size of the padded encrypted data. It varies between <plain_len> + (1~31).
@param[in] iv_ptr
16-byte initial vector.
@param[in] data_ptr
Plain data to encrypt.
@param[in] data_len
Length (in byte) of <data_ptr>.\n
If <data_len> is 0, nothing is encrypted.
*******************************************************************************/
__BOATSTATIC BOAT_RESULT KeystoreEncrypt(BOAT_OUT BUINT8 *encrypted_ptr, BOAT_INOUT BUINT32 *encrypted_len_ptr, const BUINT8 *iv_ptr, const BUINT8 *plain_ptr, BUINT32 plain_len)
{
#if BOAT_USE_OPENSSL != 0
BUINT32 encrypted_total_len = 0;
#if OPENSSL_VERSION_NUMBER < 0x10100000L
EVP_CIPHER_CTX ctx;
EVP_CIPHER_CTX *ctx_ptr = &ctx;
#else
EVP_CIPHER_CTX *ctx_ptr = NULL;
#endif
int openssl_ret;
int openssl_len = 0;
#endif
BOAT_RESULT result = BOAT_ERROR;
if( ( encrypted_ptr == NULL || encrypted_len_ptr == NULL || iv_ptr == NULL || plain_ptr == NULL ) && plain_len != 0 )
{
return BOAT_ERROR_INVALID_ARGUMENT;
}
if( plain_len == 0 )
{
*encrypted_len_ptr = 0;
return BOAT_SUCCESS;
}
#if BOAT_USE_OPENSSL != 0
if( *encrypted_len_ptr < plain_len + AES_BLOCK_SIZE * 2 - 1 )
{
// Output buffer size must reserve at least AES_BLOCK_SIZE * 2 - 1 bytes for PKCS padding
return BOAT_ERROR;
}
// Initialize OpenSSL EVP context for cipher/decipher
#if OPENSSL_VERSION_NUMBER < 0x10100000L
EVP_CIPHER_CTX_init(ctx_ptr);
#else
ctx_ptr = EVP_CIPHER_CTX_new();
#endif
if( ctx_ptr != NULL )
{
// Specify AES256-CBC Algorithm, AES key and initial vector of CBC
openssl_ret = EVP_EncryptInit_ex(ctx_ptr, EVP_aes_256_cbc(), NULL, g_aes_key, iv_ptr);
if( openssl_ret == 1 )
{
encrypted_total_len = 0;
// Encryption update
openssl_ret = EVP_EncryptUpdate(ctx_ptr, encrypted_ptr, &openssl_len, plain_ptr, plain_len);
if( openssl_ret == 1 )
{
encrypted_total_len += openssl_len;
// Finalize encryption
openssl_ret = EVP_EncryptFinal_ex(ctx_ptr, encrypted_ptr + encrypted_total_len, &openssl_len);
if( openssl_ret == 1 )
{
encrypted_total_len += openssl_len;
*encrypted_len_ptr = encrypted_total_len;
result = BOAT_SUCCESS;
}
}
}
}
#if OPENSSL_VERSION_NUMBER < 0x10100000L
EVP_CIPHER_CTX_cleanup(&ctx);
#else
if( ctx_ptr != NULL )
{
EVP_CIPHER_CTX_free(ctx_ptr);
}
#endif
#else // BOAT_USE_OPENSSL != 0
BSINT32 i;
if( *encrypted_len_ptr < plain_len )
{
return BOAT_ERROR;
}
for( i = 0; i < plain_len; i++ )
{
encrypted_ptr[i] = plain_ptr[i] ^ g_aes_key[i%sizeof(g_aes_key)];
*encrypted_len_ptr = plain_len;
}
result = BOAT_SUCCESS;
#endif // BOAT_USE_OPENSSL != 0
return result;
}
/******************************************************************************
@brief AES decryption wrapper
Function: KeystoreDecrypt()
This function decrypts the data with AES-256 CBC.
In case OpenSSL is not availble, it simply decodes the data in a compatible
format without actual decryption.
It's for internally use only.
@see KeystoreEncrypt()
@return
This function returns BOAT_SUCCESS if it successfully decrypts the data.\n
Otherwise it returns one of the error codes.
@param[out] plain_ptr
Output buffer of the decrypted plain data.
@param[inout] plain_len_ptr
In: The size of <plain_ptr>.\n
Out: The actual size of plain data after removing the padding.
@param[in] iv_ptr
16-byte initial vector.
@param[in] encrypted_ptr
Encrypted data to decrypt.
@param[in] encrypted_len
Length (in byte) of <encrypted_ptr>.\n
If <encrypted_len> is 0, nothing is decrypted.
*******************************************************************************/
__BOATSTATIC BOAT_RESULT KeystoreDecrypt(BOAT_OUT BUINT8 *plain_ptr, BOAT_INOUT BUINT32 *plain_len_ptr, const BUINT8 *iv_ptr, const BUINT8 *encrypted_ptr, BUINT32 encrypted_len)
{
#if BOAT_USE_OPENSSL != 0
BUINT32 plain_total_len = 0;
BUINT8 temp_plain_array[encrypted_len];
#if OPENSSL_VERSION_NUMBER < 0x10100000L
EVP_CIPHER_CTX ctx;
EVP_CIPHER_CTX *ctx_ptr = &ctx;
#else
EVP_CIPHER_CTX *ctx_ptr = NULL;
#endif
int openssl_ret;
int openssl_len;
#endif
BOAT_RESULT result = BOAT_ERROR;
if( ( plain_ptr == NULL || plain_len_ptr == NULL || iv_ptr == NULL || encrypted_ptr == NULL ) && encrypted_len != 0 )
{
return BOAT_ERROR_INVALID_ARGUMENT;
}
if( encrypted_len == 0 )
{
*plain_len_ptr = 0;
return BOAT_SUCCESS;
}
#if BOAT_USE_OPENSSL != 0
// Initialize OpenSSL EVP context for cipher/decipher
#if OPENSSL_VERSION_NUMBER < 0x10100000L
EVP_CIPHER_CTX_init(ctx_ptr);
#else
ctx_ptr = EVP_CIPHER_CTX_new();
#endif
if( ctx_ptr != NULL )
{
// Specify AES256-CBC Algorithm, AES key and initial vector of CBC
openssl_ret = EVP_DecryptInit_ex(ctx_ptr, EVP_aes_256_cbc(), NULL, g_aes_key, iv_ptr);
if( openssl_ret == 1 )
{
plain_total_len = 0;
// Decryption update
openssl_ret = EVP_DecryptUpdate(ctx_ptr, temp_plain_array, &openssl_len, encrypted_ptr, encrypted_len);
if( openssl_ret == 1 )
{
plain_total_len += openssl_len;
// Finalize encryption
openssl_ret = EVP_DecryptFinal_ex(ctx_ptr, temp_plain_array + plain_total_len, &openssl_len);
if( openssl_ret == 1 )
{
plain_total_len += openssl_len;
// Check output buffer size
if( *plain_len_ptr >= plain_total_len )
{
*plain_len_ptr = plain_total_len;
memcpy(plain_ptr, temp_plain_array, plain_total_len);
result = BOAT_SUCCESS;
}
}
}
}
}
#if OPENSSL_VERSION_NUMBER < 0x10100000L
EVP_CIPHER_CTX_cleanup(&ctx);
#else
if( ctx_ptr != NULL )
{
EVP_CIPHER_CTX_free(ctx_ptr);
}
#endif
#else // BOAT_USE_OPENSSL != 0
BSINT32 i;
if( *plain_len_ptr < encrypted_len )
{
return BOAT_ERROR;
}
for( i = 0; i < encrypted_len; i++ )
{
plain_ptr[i] = encrypted_ptr[i] ^ g_aes_key[i%sizeof(g_aes_key)];
*plain_len_ptr = encrypted_len;
}
result = BOAT_SUCCESS;
#endif // BOAT_USE_OPENSSL != 0
return result;
}
/*!*****************************************************************************
@brief Persitently store data in an encrypted file
Function: BoatPersistStore()
This function persistently stores data in an encrypted file with hash check.
NOTE:
This is a default implementation for persistent storage with AES-256
encryption. It assumes filesystem is supported in the system.
In case filesystem is not supported, or some type of secure enclave is equipped,
re-implement this function according to the system configuration.
This function encrypts the data and saves them into the specified file in
following format.
@verbatim
File format:\n
--------------------------------------------------------------------------
| 16 byte salt | 32 byte hash | AES(plain_data) | 0~31 byte AES paddiing |
--------------------------------------------------------------------------
^ ^ ^ ^
| | | |-> Padding within 1~31
| | | | bytes
| | |
| | |-> AES256 encrypted data (the same size as
| | the plain data), followed by padding
| |
| |-> 32-byte SHA3 hash: keccak256(plain_data)
|
|-> 16-byte random salt, used as initial vector of AEC_CBC
@endverbatim
Fields Explanation
[SALT]
The beginning of the file is a 16-byte random salt field. The salt is used as
the Initial Vector (IV) of the AES256_CBC encryption algorithm. The randomness
of the IV is a security factor. With identical IV, identical plain text
always generates identical encrypted text against identical crypto key. Thus
in turn the attacker may infer some information of the plain text from the
encrypted text. Random IV generates different encrypted text even if the
plain text is identical.
[HASH]
The second field is a 32-byte keccak256 hash (the same keccak256 as the one
used by Ethereum). To verify the data in decryption phase, the hash of the
plain data is saved in the file. If any of the encrypted data, IV or the AES
key is corrupted, the hash of the decrypted data definitely diffs from the
original one.
[AES256 ENCRYPTED DATA]
The third field is the encrypted data by AES-256 CBC.
AES is a block cipher algorithm with a block size of 16 bytes. To encrypt
plain text of any size, some block cipher mode of operation is performed.
AES-CBC is one of the most popular modes. It XORs every plain text block
with the previous encrypted text block and encrypts the XORed block. For
the first plain text block, an extra 16-byte Initial Vector (IV) is XORed.
To decrypt an encrypted block, first decrypt the block with the same AES
key and then XOR the decrypted text with the encrypted text of the previous
block. This recovers the plain text block.
To decrypt the first encrypted block (whose corresponding plain text block
was XORed with IV before being encrypted), the same IV as the one at
encryption time must be specified.
[PKCS PADDING]
The fourth field is padding as per OpenSSL rules.
OpenSSL uses PKCS#7 padding rule for AES by default. As AES's block size is
16 bytes, the rule adds 1-to-16-byte padding with every byte's value equal
to how many bytes the padding is. For example, if 6 bytes are added as
padding, the value of every byte is 0x06. Especally if no padding is required,
this rule always adds a 16-byte padding. When decrypting, OpenSSL will check
the padding value against PKCS#7 rule as a simple validition and automatically
removes PKCS#7 padding by default.
Besides the PKCS#7 padding, there is an extra 0-to-15-byte padding for data
alignment.
Thus the total padding size varies between 1~31 bytes. The output buffer
must have enough room to hold the encrypted data.
@see BoatPersistRead()
@return
This function returns BOAT_SUCCESS if it successfully stores the data.\n
Otherwise it returns one of the error codes.
@param[in] storage_name_str
The file name to store the data.
@param[in] data_ptr
The plain data to save into file.
@param[in] data_len
Length (in byte) of <data_ptr>.\n
If <data_len> is 0, no file will be created.
*******************************************************************************/
BOAT_RESULT BoatPersistStore(const BCHAR *storage_name_str, const void *data_ptr, BUINT32 data_len)
{
// Storage format: | 16 byte salt | 32 byte hash | AES(data) | 1~31 byte AES paddiing |
// Where, hash = keccak256(data)
BUINT8 salt_array[BOAT_STORAGE_SALT_SIZE];
BUINT8 data_hash_array[32];
BUINT8 encrypted_array[data_len + 31]; // 31 for AES padding
BUINT32 encrypted_len = sizeof(encrypted_array);
FILE *file_ptr;
BSINT32 count = 0;
BOAT_RESULT result;
if( storage_name_str == NULL || (data_ptr == NULL && data_len != 0 ) )
{
return BOAT_ERROR;
}
if( data_len == 0 )
{
return BOAT_SUCCESS;
}
// Calculate data hash
keccak_256(data_ptr, data_len, data_hash_array);
// Generate 16-byte salt as AES initial vector
random_stream(salt_array, BOAT_STORAGE_SALT_SIZE);
// Encrypt the data
result = KeystoreEncrypt(encrypted_array, &encrypted_len, salt_array, data_ptr, data_len);
if( result == BOAT_SUCCESS )
{
file_ptr = fopen(storage_name_str, "wb");
if( file_ptr != NULL )
{
// Store 16-byte salt
count += fwrite(salt_array, 1, sizeof(salt_array), file_ptr);
// Store 32-byte hash
count += fwrite(data_hash_array, 1, sizeof(data_hash_array), file_ptr);
// Store AES(data) | 0~15 byte AES paddiing
count += fwrite(encrypted_array, 1, encrypted_len, file_ptr);
fclose(file_ptr);
}
}
return result;
}
/*!*****************************************************************************
@brief Read and decrypt data in an encrypted persistent file
Function: BoatPersistRead()
This function reads and decrypts data from an encrypted file (written by
BoatPersistRead()). It also checks the data hash to verify if the decrypted
data is correct.
NOTE:
This is a default implementation for persistent storage with AES-256
encryption. It assumes filesystem is supported in the system.
In case filesystem is not supported, or some type of secure enclave is equipped,
re-implement this function according to the system configuration.
See BoatPersistStore() for the detailed file format.
@see BoatPersistStore()
@return
This function returns BOAT_SUCCESS if it successfully stores the data.\n
Otherwise it returns one of the error codes.
@param[in] storage_name_str
The file name to store the data.
@param[out] data_ptr
Pointer to hold the decrypted data.
@param[in] len_to_read
Length (in byte) of the original plain data. It must be the same as the\n
<data_len> in corresponding BoatPersistStore() call.
*******************************************************************************/
BOAT_RESULT BoatPersistRead(const BCHAR *storage_name_str, BOAT_OUT void *data_ptr, BUINT32 len_to_read)
{
FILE *file_ptr;
BSINT32 file_size;
BSINT32 count = 0;
// Storage format: | 16 byte salt | 32 byte hash | AES(data) | 1~31 byte AES paddiing |
// Where, hash = keccak256(data)
BUINT8 salt_array[BOAT_STORAGE_SALT_SIZE];
BUINT8 original_data_hash_array[32];
BUINT8 data_hash_array[32];
BUINT8 encrypted_array[len_to_read + 31]; // 31 for AES padding
// Plain buffer
BUINT8 plain_array[len_to_read];
BUINT32 plain_len = sizeof(plain_array);
BOAT_RESULT result = BOAT_ERROR;
if( storage_name_str == NULL || (data_ptr == NULL && len_to_read != 0 ) )
{
return BOAT_ERROR;
}
if( len_to_read == 0 )
{
return BOAT_SUCCESS;
}
file_ptr = fopen(storage_name_str, "rb");
if( file_ptr != NULL )
{
fseek(file_ptr, 0, SEEK_END);
file_size = ftell(file_ptr);
rewind(file_ptr);
if( file_size >= BOAT_STORAGE_SALT_SIZE + sizeof(data_hash_array) + len_to_read )
{
// Read salt
count = fread(salt_array, 1, BOAT_STORAGE_SALT_SIZE, file_ptr);
// Read original data hash
count = fread(original_data_hash_array, 1, sizeof(original_data_hash_array), file_ptr);
// Read rest of the file (encrypted data)
count = fread(encrypted_array, 1, BOAT_MIN(sizeof(encrypted_array), file_size - BOAT_STORAGE_SALT_SIZE - sizeof(original_data_hash_array)), file_ptr);
result = KeystoreDecrypt(plain_array, &plain_len, salt_array, encrypted_array, count);
// Check size of the decrypted data matches the length to read
if( result == BOAT_SUCCESS && plain_len == len_to_read)
{
// Calculate data hash from the decrypted data
keccak_256(plain_array, len_to_read, data_hash_array);
// Check if decrypted hash is the same as the original one
if( 0 == memcmp(original_data_hash_array, data_hash_array, sizeof(data_hash_array)) )
{
memcpy(data_ptr, plain_array, len_to_read);
result = BOAT_SUCCESS;
}
else
{
result = BOAT_ERROR;
}
}
else
{
result = BOAT_ERROR;
}
}
fclose(file_ptr);
}
return result;
}
/*!*****************************************************************************
@brief Delete a persistent storage (file)
Function: BoatPersistDelete()
This function deletes a persistent storage (file) with given name.
@return
This function returns BOAT_SUCCESS if successful.
Otherwise it returns one of the error codes.
@param[in] storage_name_str
The storage (file) name to delete.
*******************************************************************************/
BOAT_RESULT BoatPersistDelete(const BCHAR * storage_name_str)
{
// Delete file
if( 0 != remove(storage_name_str) )
{
return BOAT_ERROR;
}
else
{
return BOAT_SUCCESS;
}
}
|
uluyol/gotools | latencybench/main_linux.c | #include <fcntl.h>
#include <linux/fs.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <unistd.h>
char __latencybench_readbuf[4096] __attribute__ ((aligned(4096)));
size_t reqbufalign(char *devpath) {
size_t align;
int fd = open(devpath, 0);
if (fd == -1) {
perror("unable to open device");
return 0;
}
if (ioctl(fd, BLKBSZGET, &align) != 0) {
perror("unable to get correct alignment");
}
close(fd);
return align;
}
unsigned long bufalign() {
return __alignof__(__latencybench_readbuf);
}
|
uluyol/gotools | latencybench/main_unix.c | <reponame>uluyol/gotools
#include <stdlib.h>
char __latencybench_readbuf[4096];
size_t reqbufalign(char *devpath) {
return 0;
}
unsigned long bufalign() {
return __alignof__(__latencybench_readbuf);
}
|
uluyol/gotools | humannum/main.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(const int argc, char **argv) {
char prettybuf[1024];
char *num = NULL;
char *pretty = prettybuf;
ssize_t i = 0;
ssize_t numlen = 0;
int nz = 0;
if (argc != 2) {
fprintf(stderr, "humannum number\n");
return 1;
}
num = argv[1];
numlen = strlen(num);
for (i = numlen - 1; i >= 0; i--) {
if (num[i] == '0') {
nz++;
} else {
break;
}
}
if (numlen > sizeof prettybuf) {
pretty = calloc(numlen, 1);
if (pretty == NULL) {
puts(num);
return 0;
}
}
if (3 <= nz && nz < 6) {
strncpy(pretty, num, numlen - 3);
pretty[numlen - 3] = 'K';
pretty[numlen - 2] = '\0';
} else if (6 <= nz && nz < 9) {
strncpy(pretty, num, numlen - 6);
pretty[numlen - 6] = 'M';
pretty[numlen - 5] = '\0';
} else if (9 <= nz && nz < 12) {
strncpy(pretty, num, numlen - 9);
pretty[numlen - 9] = 'G';
pretty[numlen - 8] = '\0';
} else if (12 <= nz) {
strncpy(pretty, num, numlen - 12);
pretty[numlen - 12] = 'T';
pretty[numlen - 11] = '\0';
} else {
pretty = num;
}
puts(pretty);
}
|
uluyol/gotools | latencybench/main.c | #include "platforms.h"
#include <fcntl.h>
#include <inttypes.h>
#include <unistd.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
static char *workpath = "latencybench.data.bin";
void usage() {
fprintf(stderr, "usage: latencybench fsize nops devpath\n");
fprintf(stderr, "\nfsize must be in MB\n");
fprintf(stderr,
"\nlatencybench will issue random 1K reads and "
"output latency measurements to stdout.\n");
fprintf(stderr,
"latencybench will create a temporary file named %s "
"in the current directory.\n", workpath);
fprintf(stderr, "Measurements will only be accurate on Linux.\n");
exit(123);
}
int64_t diff_time_us(struct timespec start, struct timespec end) {
int64_t sec_diff = end.tv_sec - start.tv_sec;
int64_t ns_diff = end.tv_nsec - start.tv_nsec;
return (int64_t)(sec_diff*1000000L + ns_diff/1000L);
}
char *getreadbuf() {
return __latencybench_readbuf;
}
int main(int argc, char **argv) {
if (argc != 4) {
usage();
}
ssize_t fsize_mb = atol(argv[1]);
int32_t nops = atoi(argv[2]);
char *devpath = argv[3];
if (fsize_mb == 0 || nops == 0) {
usage();
}
if (!IS_ACCURATE) {
fprintf(stderr, "warn: latencies will be inaccurate, see help for details\n");
} else {
fprintf(stderr, "require buffer alignment of %d, assuming %lu\n", reqbufalign(devpath), bufalign());
}
char wbuf[1024*1024];
int fdrand = open("/dev/urandom", O_RDONLY);
fprintf(stderr, "writing random data to %s\n", workpath);
int wfd = creat(workpath, 0666);
ssize_t wrote = 0;
while (wrote < fsize_mb*1024*1024) {
ssize_t got = read(fdrand, wbuf, 1024*1024);
wrote += write(wfd, wbuf, got);
}
fprintf(stderr, "wrote %ld bytes\n", (long)wrote);
close(fdrand);
close(wfd);
fprintf(stderr, "collecting latency measurements\n");
char *rbuf = getreadbuf();
int rfd = open(workpath, O_RDONLY | O_DIRECT);
if (rfd == -1) {
perror("unable to open data file");
return 3;
}
int64_t *latencies = calloc(nops, sizeof(int64_t));
for (int32_t i=0; i < nops; i++) {
struct timespec start, end;
off_t offset = rand() % (1024*1024*fsize_mb);
offset /= 4096;
offset *= 4096;
clock_gettime(CLOCK_MONOTONIC, &start);
if (lseek(rfd, offset, SEEK_SET) != offset) {
perror("unable to seek");
}
for (int sofar=0; sofar < 4096; ) {
int got = read(rfd, rbuf, 4096-sofar);
if (got == -1) {
perror("unable to read data");
}
sofar += got;
}
clock_gettime(CLOCK_MONOTONIC, &end);
latencies[i] = diff_time_us(start, end);
}
close(rfd);
remove(workpath);
for (int32_t i=0; i < nops; i++) {
printf("%" PRId64 "\n", latencies[i]);
}
}
|
uluyol/gotools | latencybench/platforms.h | <reponame>uluyol/gotools<filename>latencybench/platforms.h<gh_stars>1-10
#ifdef __linux__
#define IS_ACCURATE true
#define _GNU_SOURCE
#else
#define IS_ACCURATE false
#define O_DIRECT 0
#endif
#include <stdlib.h>
extern char __latencybench_readbuf[4096];
int reqbufalign(char *devpath);
unsigned long bufalign();
|
uluyol/gotools | runbg/runbg.c | <filename>runbg/runbg.c
#include <fcntl.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/resource.h>
#include <sys/time.h>
#include <unistd.h>
void usage(void) {
fprintf(stderr, "usage: runbg [-l logpath] -- command args...\n");
fprintf(stderr,
" -l logpath path to log stderr/stdout (default bgproc.log)\n");
fprintf(stderr, " -v enable verbose logging\n");
exit(2);
}
int main(const int argc, char **argv) {
char *logfile = "bgproc.log";
bool verbose = false;
int i, c;
while ((c = getopt(argc, argv, "hvl:")) != -1) {
switch (c) {
case 'l':
logfile = optarg;
break;
case 'v':
verbose = true;
break;
case 'h':
case '?':
printf("unkown %c\n", optopt);
usage();
break;
}
}
if (optind >= argc) {
usage();
}
char *cmd = argv[optind];
char **args = calloc(argc - optind + 1, sizeof(char *));
for (i = optind; i < argc; i++) {
args[i - optind] = argv[i];
}
if (verbose) {
fprintf(stderr, "command: %s\n", cmd);
fprintf(stderr, "narg: %d\n", argc - optind);
for (i = 0; i < argc - optind; i++)
fprintf(stderr, "arg %d: %s\n", i, args[i]);
}
int fdout = creat(logfile, 0644);
if (fdout < 0) {
perror("runbg: unable to create log file");
exit(3);
}
pid_t pid;
struct rlimit lim;
getrlimit(RLIMIT_NOFILE, &lim);
/* close all open files--NR_OPEN is overkill, but works */
for (i = 3; i < lim.rlim_cur; i++) {
close(i);
}
pid = fork();
if (pid == -1) {
return -1;
} else if (pid != 0) {
close(fdout);
exit(0);
}
/* create new session and process group */
if (setsid() == -1) {
return -1;
}
pid = fork();
if (pid == -1) {
return -1;
} else if (pid != 0) {
exit(0);
}
int fd = open("/dev/null", O_RDONLY);
fdout = creat(logfile, 0644);
dup2(fd, 0);
dup2(fdout, 1);
dup2(fdout, 2);
execvp(cmd, args);
}
|
SanctaMaria1997/mprof | args.h | <gh_stars>0
/*
BSD 2-Clause License
Copyright (c) 2019, SanctaMaria1997
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ARGS_H
#define ARGS_H
#define MAX_NUM_OPTIONS 256
#define MAX_NUM_NON_OPTIONS 256
typedef struct
{
char option[256];
char argument[256];
int index;
} Option;
typedef struct
{
char text[256];
int index;
} NonOption;
typedef struct
{
char name[256];
char short_name[256];
int takes_arg;
} OptionSpec;
void register_options(OptionSpec *ao);
int parse_options(int argc,char **argv);
Option *get_options();
NonOption *get_non_options();
int option_is(char *name,Option *option);
#endif
|
SanctaMaria1997/mprof | hamster.c | #include <stdio.h>
#include <stdlib.h>
void hamster()
{
void *p;
puts("Hi from hamster!");
p = malloc(111);
}
|
SanctaMaria1997/mprof | libmprof.c | <filename>libmprof.c
/*
BSD 2-Clause License
Copyright (c) 2019, SanctaMaria1997
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#define _GNU_SOURCE
#include <signal.h>
#include <fcntl.h>
#include <semaphore.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <dlfcn.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "dwarfy.h"
#include "mprof.h"
#include "libmprof.h"
#include "mprof_util.h"
RB_GENERATE(TransactionPointTree,TransactionPoint,TransactionPointLinks,compare_transaction_points);
RB_GENERATE(TransactionPathTree,TransactionPath,TransactionPathLinks,compare_transaction_paths_by_trace);
RB_GENERATE(TransactionPathSortedTree,TransactionPathSorted,TransactionPathSortedLinks,compare_transaction_paths_by_leaked_bytes);
RB_GENERATE(MemoryBlockTree,MemoryBlock,MemoryBlockLinks,compare_memory_blocks_by_address);
RB_GENERATE(MemoryBlockSortedTree,MemoryBlockSorted,MemoryBlockSortedLinks,compare_memory_blocks_by_size);
RB_GENERATE(MemoryBreakdownTree,MemoryBreakdown,MemoryBreakdownLinks,compare_memory_breakdowns);
RB_GENERATE(FunctionBreakdownTree,FunctionBreakdown,FunctionBreakdownLinks,compare_function_breakdowns);
RB_GENERATE(SortedLibraryTree,SortedLibrary,SortedLibraryLinks,compare_sorted_libraries);
unsigned long int LIBMPROF_TOTAL_NUM_TRANSACTIONS;
unsigned long int LIBMPROF_NUM_MALLOCS;
unsigned long int LIBMPROF_NUM_CALLOCS;
unsigned long int LIBMPROF_NUM_REALLOCS;
unsigned long int LIBMPROF_NUM_FREES;
unsigned long int LIBMPROF_TOTAL_NUM_TRANSACTIONS;
unsigned long int LIBMPROF_TOTAL_BYTES_ALLOCATED;
unsigned long int LIBMPROF_TOTAL_BYTES_FREED;
unsigned long int LIBMPROF_NUM_ALLOCATIONS_SMALL;
unsigned long int LIBMPROF_NUM_ALLOCATIONS_MEDIUM;
unsigned long int LIBMPROF_NUM_ALLOCATIONS_LARGE;
unsigned long int LIBMPROF_NUM_ALLOCATIONS_XLARGE;
unsigned long int LIBMPROF_NUM_FREES_SMALL;
unsigned long int LIBMPROF_NUM_FREES_MEDIUM;
unsigned long int LIBMPROF_NUM_FREES_LARGE;
unsigned long int LIBMPROF_NUM_FREES_XLARGE;
unsigned long int LIBMPROF_TOTAL_NUM_BYTES_SMALL;
unsigned long int LIBMPROF_TOTAL_NUM_BYTES_MEDIUM;
unsigned long int LIBMPROF_TOTAL_NUM_BYTES_LARGE;
unsigned long int LIBMPROF_TOTAL_NUM_BYTES_XLARGE;
unsigned long int LIBMPROF_CURRENT_NUM_BYTES_SMALL;
unsigned long int LIBMPROF_CURRENT_NUM_BYTES_MEDIUM;
unsigned long int LIBMPROF_CURRENT_NUM_BYTES_LARGE;
unsigned long int LIBMPROF_CURRENT_NUM_BYTES_XLARGE;
FILE *MPROF_OUTPUT_FILE;
char MPROF_OUTPUT_FILE_NAME[256];
sem_t *MPROF_INSTANCE;
sem_t *MPROF_MEM_MUTEX;
char MPROF_MEM_MUTEX_NAME[256];
LibmprofSharedMem *LIBMPROF_SHARED_MEM;
int SHMID;
long int LIBMPROF_REGION_BASE[LIBMPROF_MAX_NUM_REGIONS];
long int LIBMPROF_NUM_REGIONS;
SortedLibraryTree_t LIBMPROF_LIBS;
TransactionPointTree_t TRANSACTION_POINTS;
MemoryBreakdownTree_t MEMORY_BREAKDOWNS;
FunctionBreakdownTree_t FUNCTION_BREAKDOWNS;
DWARF_DATAList_t DWARFY_PROGRAM;
void leak_report(void);
int compare_transaction_points(TransactionPoint *a1,TransactionPoint *a2)
{
return a1->address - a2->address;
}
int compare_transaction_paths_by_trace(TransactionPath *a1,TransactionPath *a2)
{
int i;
int order;
for(i = 0; i < MPROF_TRACE_DEPTH; i++)
{
order = strcmp(a1->trace->function_names[i],a2->trace->function_names[i]);
{
if(order < 0)
return -1;
else if(order > 0)
return 1;
}
}
return 0;
}
int compare_transaction_paths_by_leaked_bytes(TransactionPathSorted *a1,TransactionPathSorted *a2)
{
return a2->current_bytes_allocated - a1->current_bytes_allocated;
}
int compare_memory_blocks_by_address(MemoryBlock *mb1,MemoryBlock *mb2)
{
return mb1->address - mb2->address;
}
int compare_memory_blocks_by_size(MemoryBlockSorted *mb1,MemoryBlockSorted *mb2)
{
return mb1->size - mb2->size;
}
int compare_memory_breakdowns(MemoryBreakdown *mb1,MemoryBreakdown *mb2)
{
return mb1->size - mb2->size;
}
int compare_function_breakdowns(FunctionBreakdown *fb1,FunctionBreakdown *fb2)
{
return strcmp(fb1->name,fb2->name);
}
int compare_sorted_libraries(SortedLibrary *sl1,SortedLibrary *sl2)
{
return strcmp(sl1->name,sl2->name);
}
SortedLibrary *copy_library(Library *lib)
{
SortedLibrary *result = malloc(sizeof(SortedLibrary));
memset(result,0,sizeof(SortedLibrary));
strcpy(result->name,lib->name);
result->dwarf = lib->dwarf;
result->base_address = lib->base_address;
return result;
}
void __attribute__((constructor)) libmprof_init()
{
int i = 0,j = 0,m = 0;
int proj;
int instance;
char name[256];
SortedLibrary *sorted_library;
LIBMPROF_NUM_MALLOCS = LIBMPROF_NUM_CALLOCS = LIBMPROF_NUM_REALLOCS = LIBMPROF_NUM_FREES = 0;
LIBMPROF_NUM_ALLOCATIONS_SMALL = LIBMPROF_NUM_ALLOCATIONS_MEDIUM = LIBMPROF_NUM_ALLOCATIONS_LARGE = LIBMPROF_NUM_ALLOCATIONS_XLARGE = LIBMPROF_NUM_FREES_SMALL = LIBMPROF_NUM_FREES_MEDIUM = LIBMPROF_NUM_FREES_LARGE = LIBMPROF_NUM_FREES_XLARGE = 0;
LIBMPROF_TOTAL_NUM_BYTES_SMALL = LIBMPROF_TOTAL_NUM_BYTES_MEDIUM = LIBMPROF_TOTAL_NUM_BYTES_LARGE = LIBMPROF_TOTAL_NUM_BYTES_XLARGE = 0;
LIBMPROF_CURRENT_NUM_BYTES_SMALL = LIBMPROF_CURRENT_NUM_BYTES_MEDIUM = LIBMPROF_CURRENT_NUM_BYTES_LARGE = LIBMPROF_CURRENT_NUM_BYTES_XLARGE = 0;
LIBMPROF_TOTAL_NUM_TRANSACTIONS = 0;
LIBMPROF_TOTAL_BYTES_ALLOCATED = 0;
RB_INIT(&TRANSACTION_POINTS);
RB_INIT(&MEMORY_BREAKDOWNS);
RB_INIT(&FUNCTION_BREAKDOWNS);
RB_INIT(&LIBMPROF_LIBS);
MPROF_INSTANCE = sem_open("/mprof_instance",O_CREAT,0666,0);
sem_getvalue(MPROF_INSTANCE,&instance);
sprintf(MPROF_MEM_MUTEX_NAME,"/mprof_mem_mutex.%d",instance);
MPROF_MEM_MUTEX = sem_open(MPROF_MEM_MUTEX_NAME,O_CREAT,0666,1);
sprintf(MPROF_OUTPUT_FILE_NAME,"tables.mprof.%d",instance);
SHMID = shmget(ftok(MPROF_OUTPUT_FILE_NAME,1),sizeof(LibmprofSharedMem),0666);
LIBMPROF_SHARED_MEM = shmat(SHMID,0,0);
if(LIBMPROF_SHARED_MEM->config.output_to_stderr)
MPROF_OUTPUT_FILE = stderr;
else
MPROF_OUTPUT_FILE = fopen(MPROF_OUTPUT_FILE_NAME,"w");
sem_post(MPROF_INSTANCE);
raise(SIGTRAP);
while(strlen(LIBMPROF_SHARED_MEM->libraries[i].name))
{
if(LIBMPROF_SHARED_MEM->libraries[i].name[0] != '/')
{
strcpy(name,file_part(LIBMPROF_SHARED_MEM->libraries[i].name));
if(0 == strcmp(name,"libmprof.so"))
{
LIBMPROF_SHARED_MEM->libraries[i].dwarf = load_dwarf("/usr/local/lib/libmprof.so",LIBMPROF_SHARED_MEM->libraries[i].base_address);
}
else if(strlen(find_file(name,".")))
{
LIBMPROF_SHARED_MEM->libraries[i].dwarf = load_dwarf(find_file(name,"."),LIBMPROF_SHARED_MEM->libraries[i].base_address);
if(LIBMPROF_SHARED_MEM->libraries[i].dwarf == 0)
{
fprintf(stderr,"[mprof] Unable to load DWARF debug information from object \"%s\". Consider recompiling with -g to generate debug information.",LIBMPROF_SHARED_MEM->libraries[i].name);
exit(1);
}
}
sorted_library = copy_library(&LIBMPROF_SHARED_MEM->libraries[i]);
RB_INSERT(SortedLibraryTree,&LIBMPROF_LIBS,sorted_library);
}
i++;
}
i = 0;
m = 0;
DwarfyCompilationUnit *compilation_unit;
while(strlen(LIBMPROF_SHARED_MEM->libraries[i].name))
{
if(LIBMPROF_SHARED_MEM->libraries[i].dwarf)
{
LIST_FOREACH(compilation_unit,&LIBMPROF_SHARED_MEM->libraries[i].dwarf->compilation_units,linkage)
{
if(compilation_unit->has_main_function)
{
m = 1;
goto exit;
}
}
}
i++;
}
exit:
if(m == 0)
{
fprintf(stderr,"[mprof] Unable to load DWARF debug information from object. Consider recompiling with -g to generate debug information.");
exit(1);
}
}
TransactionPoint *create_transaction_point(int transaction_type,long int address)
{
TransactionPoint *transaction_point;
transaction_point = malloc(sizeof(TransactionPoint));
memset(transaction_point,0,sizeof(TransactionPoint));
transaction_point->transaction_type = transaction_type;
transaction_point->address = address;
RB_INIT(&transaction_point->paths);
RB_INSERT(TransactionPointTree,&TRANSACTION_POINTS,transaction_point);
return transaction_point;
}
TransactionPath *create_transaction_path(int transaction_type,Backtrace *trace,TransactionPoint *transaction_point)
{
TransactionPath *transaction_path;
transaction_path = malloc(sizeof(TransactionPath));
memset(transaction_path,0,sizeof(TransactionPath));
transaction_path->transaction_point = transaction_point;
transaction_path->trace = malloc(sizeof(Backtrace));
memcpy(transaction_path->trace,trace,sizeof(Backtrace));
RB_INIT(&transaction_path->memory_blocks);
RB_INSERT(TransactionPathTree,&transaction_point->paths,transaction_path);
return transaction_path;
}
MemoryBlock *create_memory_block(unsigned long int address,size_t size,TransactionPath *transaction_path)
{
MemoryBlock *memory_block;
memory_block = malloc(sizeof(MemoryBlock));
memory_block->address = address;
memory_block->size = size;
memory_block->path = transaction_path;
RB_INSERT(MemoryBlockTree,&transaction_path->memory_blocks,memory_block);
return memory_block;
}
Backtrace *create_backtrace()
{
Backtrace *backtrace = malloc(sizeof(Backtrace));
memset(backtrace,0,sizeof(Backtrace));
return backtrace;
}
void trace_(unsigned long int *frame_pointer,Backtrace *trace,int depth)
{
DwarfyFunction *function;
DwarfyCompilationUnit *compilation_unit;
DwarfySourceRecord *source_record;
unsigned long int address;
char location[256];
char best_symbolic_name[256];
char tmp[5];
char *elipsis = "...";
Dl_info info;
address = *(frame_pointer + 1);
if(0 == dladdr((void*)address,&info))
{
puts("[mprof] Invalid frame pointer detected; consider recompiling this program without optimisations.");
exit(1);
}
compilation_unit = address_to_compilation_unit(address);
function = address_to_function(address,compilation_unit);
source_record = address_to_source_record(address,compilation_unit);
if(function)
{
strcpy(best_symbolic_name,function->name);
}
else
{
strcpy(best_symbolic_name,"?@");
strcat(best_symbolic_name,file_part(info.dli_fname));
}
strcat(best_symbolic_name,"()");
if(LIBMPROF_SHARED_MEM->config.call_sites && compilation_unit)
{
sprintf(location," [%s:%d] ",compilation_unit->file_names[source_record->file - 1],source_record->line_number);
}
else
sprintf(location,"");
strcpy(trace->function_names[depth],best_symbolic_name);
strcat(trace->function_names[depth],location);
strcpy(tmp,best_symbolic_name);
tmp[4] = 0;
if(strcmp(tmp,"main"))
{
if(depth == MPROF_TRACE_DEPTH - 1)
trace->too_deep = 1;
else if(function)
trace_((unsigned long int*)*frame_pointer,trace,depth + 1);
}
}
void update_alloc_bins(size_t size)
{
if(size <= 32)
{
LIBMPROF_NUM_ALLOCATIONS_SMALL++;
LIBMPROF_TOTAL_NUM_BYTES_SMALL += size;
LIBMPROF_CURRENT_NUM_BYTES_SMALL += size;
}
else if(size <= 256)
{
LIBMPROF_NUM_ALLOCATIONS_MEDIUM++;
LIBMPROF_TOTAL_NUM_BYTES_MEDIUM += size;
LIBMPROF_CURRENT_NUM_BYTES_MEDIUM += size;
}
else if(size <= 2048)
{
LIBMPROF_NUM_ALLOCATIONS_LARGE++;
LIBMPROF_TOTAL_NUM_BYTES_LARGE += size;
LIBMPROF_CURRENT_NUM_BYTES_LARGE += size;
}
else
{
LIBMPROF_NUM_ALLOCATIONS_XLARGE++;
LIBMPROF_TOTAL_NUM_BYTES_XLARGE += size;
LIBMPROF_CURRENT_NUM_BYTES_XLARGE += size;
}
}
void update_free_bins(size_t size)
{
if(size <= 32)
{
LIBMPROF_NUM_FREES_SMALL++;
LIBMPROF_CURRENT_NUM_BYTES_SMALL -= size;
}
else if(size <= 256)
{
LIBMPROF_NUM_FREES_MEDIUM++;
LIBMPROF_CURRENT_NUM_BYTES_MEDIUM -= size;
}
else if(size <= 2048)
{
LIBMPROF_NUM_FREES_LARGE++;
LIBMPROF_CURRENT_NUM_BYTES_LARGE -= size;
}
else
{
LIBMPROF_NUM_FREES_XLARGE++;
LIBMPROF_CURRENT_NUM_BYTES_XLARGE -= size;
}
}
void update_memory_breakdowns_with_alloc(size_t size)
{
MemoryBreakdown *memory_breakdown;
MemoryBreakdown match_memory_breakdown;
match_memory_breakdown.size = size;
if(0 == (memory_breakdown = RB_FIND(MemoryBreakdownTree,&MEMORY_BREAKDOWNS,&match_memory_breakdown)))
{
memory_breakdown = malloc(sizeof(MemoryBreakdown));
memset(memory_breakdown,0,sizeof(MemoryBreakdown));
memory_breakdown->size = size;
RB_INSERT(MemoryBreakdownTree,&MEMORY_BREAKDOWNS,memory_breakdown);
}
memory_breakdown->total_num_allocs++;
memory_breakdown->current_bytes_allocated += size;
memory_breakdown->total_bytes_allocated += size;
}
void update_memory_breakdowns_with_free(MemoryBlock *memory_block)
{
MemoryBreakdown *memory_breakdown;
MemoryBreakdown match_memory_breakdown;
match_memory_breakdown.size = memory_block->size;
if(0 == (memory_breakdown = RB_FIND(MemoryBreakdownTree,&MEMORY_BREAKDOWNS,&match_memory_breakdown)))
{
memory_breakdown = malloc(sizeof(MemoryBreakdown));
memset(memory_breakdown,0,sizeof(MemoryBreakdown));
memory_breakdown->size = memory_block->size;
}
memory_breakdown->current_bytes_allocated -= memory_block->size;
memory_breakdown->total_num_frees++;
}
void update_function_breakdowns_with_alloc(unsigned long int *frame_pointer,size_t size)
{
DwarfyFunction *function;
unsigned long int address;
FunctionBreakdown *function_breakdown;
FunctionBreakdown match_function_breakdown;
DwarfyCompilationUnit *compilation_unit;
address = *(frame_pointer + 1);
compilation_unit = address_to_compilation_unit(address);
function = address_to_function(address,compilation_unit);
if(function == 0)
return;
match_function_breakdown.name = function->name;
if(0 == (function_breakdown = RB_FIND(FunctionBreakdownTree,&FUNCTION_BREAKDOWNS,&match_function_breakdown)))
{
function_breakdown = malloc(sizeof(FunctionBreakdown));
memset(function_breakdown,0,sizeof(FunctionBreakdown));
function_breakdown->name = malloc(strlen(function->name) + 1);
strcpy(function_breakdown->name,function->name);
RB_INSERT(FunctionBreakdownTree,&FUNCTION_BREAKDOWNS,function_breakdown);
}
function_breakdown->num_calls++;
function_breakdown->total_bytes_allocated += size;
function_breakdown->current_bytes_allocated += size;
if(size <= 32)
function_breakdown->num_allocations_small++;
else if(size <= 256)
function_breakdown->num_allocations_medium++;
else if(size <= 2048)
function_breakdown->num_allocations_large++;
else
function_breakdown->num_allocations_xlarge++;
}
void update_function_breakdowns_with_free(unsigned long int *frame_pointer,MemoryBlock *memory_block)
{
DwarfyFunction *orig_function, *curr_function;
DwarfyCompilationUnit *compilation_unit;
unsigned long int address;
FunctionBreakdown *curr_function_breakdown, *orig_function_breakdown;
FunctionBreakdown match_function_breakdown;
unsigned long int curr_address,orig_address;
curr_address = *(frame_pointer + 1);
compilation_unit = address_to_compilation_unit(curr_address);
curr_function = address_to_function(curr_address,compilation_unit);
orig_address = memory_block->path->transaction_point->address + 1;
compilation_unit = address_to_compilation_unit(orig_address);
orig_function = address_to_function(orig_address,compilation_unit);
if(curr_function == 0 || orig_function == 0)
return;
match_function_breakdown.name = curr_function->name;
if(0 == (curr_function_breakdown = RB_FIND(FunctionBreakdownTree,&FUNCTION_BREAKDOWNS,&match_function_breakdown)))
{
curr_function_breakdown = malloc(sizeof(FunctionBreakdown));
memset(curr_function_breakdown,0,sizeof(FunctionBreakdown));
curr_function_breakdown->name = malloc(strlen(curr_function->name) + 1);
strcpy(curr_function_breakdown->name,curr_function->name);
RB_INSERT(FunctionBreakdownTree,&FUNCTION_BREAKDOWNS,curr_function_breakdown);
}
match_function_breakdown.name = orig_function->name;
if(0 == (orig_function_breakdown = RB_FIND(FunctionBreakdownTree,&FUNCTION_BREAKDOWNS,&match_function_breakdown)))
{
orig_function_breakdown = malloc(sizeof(FunctionBreakdown));
memset(orig_function_breakdown,0,sizeof(FunctionBreakdown));
orig_function_breakdown->name = malloc(strlen(orig_function->name) + 1);
strcpy(orig_function_breakdown->name,orig_function->name);
RB_INSERT(FunctionBreakdownTree,&FUNCTION_BREAKDOWNS,orig_function_breakdown);
}
curr_function_breakdown->num_calls++;
if(memory_block->size > orig_function_breakdown->current_bytes_allocated)
orig_function_breakdown->current_bytes_allocated = 0; // prevent integer wrap around due to invalid frees
else
orig_function_breakdown->current_bytes_allocated -= memory_block->size;
if(memory_block->size <= 32)
orig_function_breakdown->num_frees_small++;
else if(memory_block->size <= 256)
orig_function_breakdown->num_frees_medium++;
else if(memory_block->size <= 2048)
orig_function_breakdown->num_frees_large++;
else
orig_function_breakdown->num_frees_xlarge++;
}
void *mprof_g_malloc(size_t size)
{
return mprof_malloc(size);
}
void *mprof_g_malloc0(size_t size)
{
return mprof_malloc(size);
}
void *mprof_g_malloc_n(size_t num,size_t size)
{
return mprof_calloc(num,size);
}
void *mprof_g_realloc(void *ptr,size_t size)
{
return mprof_realloc(ptr,size);
}
void *mprof_g_realloc_n(void *ptr,size_t num,size_t size)
{
return mprof_realloc(ptr,num * size);
}
void *mprof_g_try_malloc(size_t size)
{
void *result;
if(0 == (result = mprof_malloc(size)));
{
fprintf(stderr,"[mprof] g_try_malloc() failed (out of memory).");
exit(1);
}
return result;
}
void *mprof_g_try_malloc0(size_t size)
{
void *result;
if(0 == (result = mprof_malloc(size)));
{
fprintf(stderr,"[mprof] mprof_g_try_malloc0() failed.");
exit(1);
}
return result;
}
void *mprof_g_try_realloc(size_t size)
{
void *result;
if(0 == (result = mprof_malloc(size)));
{
fprintf(stderr,"[mprof] mprof_g_try_realloc() failed.");
exit(1);
}
return result;
}
void *mprof_g_try_malloc_n(size_t num,size_t size)
{
void *result;
if(0 == (result = mprof_malloc(num * size)));
{
fprintf(stderr,"[mprof] mprof_g_try_malloc_n() failed.");
exit(1);
}
return result;
}
void *mprof_g_try_malloc0_n(size_t num,size_t size)
{
void *result;
if(0 == (result = mprof_malloc(num * size)));
{
fprintf(stderr,"[mprof] mprof_g_try_malloc0_n() failed.");
exit(1);
}
return result;
}
void *mprof_g_try_realloc_n(void *mem,size_t num,size_t size)
{
void *result;
if(0 == (result = mprof_realloc(mem,num * size)));
{
fprintf(stderr,"[mprof] mprof_g_try_realloc_n() failed.");
exit(1);
}
return result;
}
void mprof_g_free(void *mem)
{
mprof_free(mem);
}
void *mprof_malloc(size_t size)
{
sem_wait(MPROF_MEM_MUTEX);
void *result;
long int return_address = 0;
long int transaction_address;
Backtrace *trace;
unsigned long int *frame_pointer;
TransactionPoint match_transaction_point;
TransactionPoint *transaction_point;
TransactionPath match_transaction_path;
TransactionPath *transaction_path;
MemoryBlock *memory_block;
DwarfyFunction *parent_function;
DwarfyCompilationUnit *compilation_unit;
__asm__
(
"movq %%rbp, %0\n"
: [frame_pointer] "=r"(frame_pointer)
);
if(LIBMPROF_SHARED_MEM->config.gnu)
frame_pointer = (unsigned long int*)(*frame_pointer);
trace = create_backtrace();
trace_(frame_pointer,trace,0);
return_address = *(frame_pointer + 1);
compilation_unit = address_to_compilation_unit(return_address);
parent_function = address_to_function(return_address,compilation_unit);
if(LIBMPROF_SHARED_MEM->config.call_sites || parent_function == 0)
match_transaction_point.address = return_address;
else
match_transaction_point.address = parent_function->address;
match_transaction_path.trace = trace;
if(0 == (transaction_point = RB_FIND(TransactionPointTree,&TRANSACTION_POINTS,&match_transaction_point)))
{
transaction_point = create_transaction_point(TRANSACTION_TYPE_GENERIC,match_transaction_point.address);
transaction_path = create_transaction_path(TRANSACTION_TYPE_GENERIC,trace,transaction_point);
}
else if(0 == (transaction_path = RB_FIND(TransactionPathTree,&transaction_point->paths,&match_transaction_path)))
{
transaction_path = create_transaction_path(TRANSACTION_TYPE_GENERIC,trace,transaction_point);
}
transaction_path->current_num_transactions++;
transaction_path->current_bytes_allocated += size;
transaction_path->total_num_transactions++;
transaction_path->total_bytes_allocated += size;
result = malloc(size);
memset(result,0,size);
memory_block = create_memory_block((unsigned long int)result,size,transaction_path);
LIBMPROF_TOTAL_NUM_TRANSACTIONS++;
LIBMPROF_NUM_MALLOCS++;
LIBMPROF_TOTAL_BYTES_ALLOCATED += size;
update_alloc_bins(size);
update_memory_breakdowns_with_alloc(size);
update_function_breakdowns_with_alloc(frame_pointer,size);
free(trace);
sem_post(MPROF_MEM_MUTEX);
return result;
}
void *mprof_calloc(size_t num,size_t size)
{
sem_wait(MPROF_MEM_MUTEX);
void *result;
long int return_address = 0;
long int transaction_address;
unsigned long int *frame_pointer;
TransactionPoint match_transaction_point;
TransactionPoint *transaction_point;
TransactionPath match_transaction_path;
TransactionPath *transaction_path;
Backtrace *trace;
MemoryBlock *memory_block;
DwarfyFunction *parent_function;
DwarfyCompilationUnit *compilation_unit;
__asm__
(
"movq %%rbp, %0\n"
: [frame_pointer] "=r"(frame_pointer)
);
if(LIBMPROF_SHARED_MEM->config.gnu)
frame_pointer = (unsigned long int*)(*frame_pointer);
trace = create_backtrace();
trace_(frame_pointer,trace,0);
return_address = *(frame_pointer + 1);
compilation_unit = address_to_compilation_unit(return_address);
parent_function = address_to_function(return_address,compilation_unit);
if(LIBMPROF_SHARED_MEM->config.call_sites || parent_function == 0)
match_transaction_point.address = return_address;
else
match_transaction_point.address = parent_function->address;
match_transaction_path.trace = trace;
if(0 == (transaction_point = RB_FIND(TransactionPointTree,&TRANSACTION_POINTS,&match_transaction_point)))
{
transaction_point = create_transaction_point(TRANSACTION_TYPE_GENERIC,match_transaction_point.address);
transaction_path = create_transaction_path(TRANSACTION_TYPE_GENERIC,trace,transaction_point);
}
else if(0 == (transaction_path = RB_FIND(TransactionPathTree,&transaction_point->paths,&match_transaction_path)))
transaction_path = create_transaction_path(TRANSACTION_TYPE_GENERIC,trace,transaction_point);
transaction_path->current_num_transactions++;
transaction_path->current_bytes_allocated += num * size;
transaction_path->total_num_transactions++;
transaction_path->total_bytes_allocated += num * size;
result = calloc(num,size);
memset(result,0,num * size);
memory_block = create_memory_block((unsigned long int)result,num * size,transaction_path);
LIBMPROF_TOTAL_NUM_TRANSACTIONS++;
LIBMPROF_NUM_CALLOCS++;
LIBMPROF_TOTAL_BYTES_ALLOCATED += num * size;
update_alloc_bins(num * size);
update_memory_breakdowns_with_alloc(num * size);
update_function_breakdowns_with_alloc(frame_pointer,num * size);
free(trace);
sem_post(MPROF_MEM_MUTEX);
return result;
}
void *mprof_realloc(void *ptr,size_t size)
{
sem_wait(MPROF_MEM_MUTEX);
void *result;
long int return_address = 0;
long int size_difference = 0;
unsigned long int *frame_pointer;
Backtrace *trace;
unsigned long int block_size_increase;
TransactionPoint match_transaction_point;
TransactionPoint *transaction_point;
TransactionPath match_transaction_path;
TransactionPath *transaction_path;
MemoryBlock *memory_block,match_memory_block;
DwarfyFunction *parent_function;
DwarfyCompilationUnit *compilation_unit;
match_memory_block.address = (unsigned long int)ptr;
if(ptr == 0)
{
sem_post(MPROF_MEM_MUTEX);
return mprof_malloc(size);
}
__asm__
(
"movq %%rbp, %0\n"
: [frame_pointer] "=r"(frame_pointer)
);
if(LIBMPROF_SHARED_MEM->config.gnu)
frame_pointer = (unsigned long int*)(*frame_pointer);
trace = create_backtrace();
trace_(frame_pointer,trace,0);
return_address = *(frame_pointer + 1);
memory_block = 0;
RB_FOREACH(transaction_point,TransactionPointTree,&TRANSACTION_POINTS)
{
RB_FOREACH(transaction_path,TransactionPathTree,&transaction_point->paths)
{
if((memory_block = RB_FIND(MemoryBlockTree,&transaction_path->memory_blocks,&match_memory_block)))
goto exit;
}
}
exit:
if(memory_block == 0)
return realloc(ptr,size);
size_difference = ((long int)size) - ((long int)(memory_block->size));
compilation_unit = address_to_compilation_unit(return_address);
parent_function = address_to_function(return_address,compilation_unit);
if(LIBMPROF_SHARED_MEM->config.call_sites || parent_function == 0)
match_transaction_point.address = return_address;
else
match_transaction_point.address = parent_function->address;
match_transaction_path.trace = trace;
if(0 == (transaction_point = RB_FIND(TransactionPointTree,&TRANSACTION_POINTS,&match_transaction_point)))
{
transaction_point = create_transaction_point(TRANSACTION_TYPE_GENERIC,match_transaction_point.address);
transaction_path = create_transaction_path(TRANSACTION_TYPE_GENERIC,trace,transaction_point);
}
if(0 == (transaction_path = RB_FIND(TransactionPathTree,&transaction_point->paths,&match_transaction_path)))
transaction_path = create_transaction_path(TRANSACTION_TYPE_GENERIC,trace,transaction_point);
if(transaction_path != memory_block->path)
{
RB_REMOVE(MemoryBlockTree,&memory_block->path->memory_blocks,memory_block);
memory_block->path->current_bytes_allocated -= memory_block->size;
memory_block->path->current_num_transactions--;
RB_INSERT(MemoryBlockTree,&transaction_path->memory_blocks,memory_block);
}
transaction_path->current_bytes_allocated += size;
transaction_path->total_bytes_allocated += size;
transaction_path->current_num_transactions++;
transaction_path->total_num_transactions++;
result = realloc(ptr,size);
memory_block->address = (unsigned long int)result;
memory_block->size = size;
memory_block->path = transaction_path;
block_size_increase = size_difference > 0 ? size_difference : 0;
LIBMPROF_TOTAL_NUM_TRANSACTIONS++;
LIBMPROF_NUM_REALLOCS++;
LIBMPROF_TOTAL_BYTES_ALLOCATED += block_size_increase;
update_alloc_bins(block_size_increase);
update_memory_breakdowns_with_alloc(block_size_increase);
update_function_breakdowns_with_alloc(frame_pointer,block_size_increase);
free(trace);
sem_post(MPROF_MEM_MUTEX);
return result;
}
void mprof_free(void *ptr)
{
sem_wait(MPROF_MEM_MUTEX);
MemoryBlock match;
MemoryBlock *memory_block;
TransactionPoint *transaction_point;
TransactionPath *transaction_path;
TransactionPoint match_transaction_point;
TransactionPath *orig_transaction_path;
TransactionPoint *orig_transaction_point;
TransactionPath match_transaction_path;
DwarfyFunction *parent_function;
DwarfyCompilationUnit *compilation_unit;
long int return_address = 0;
Backtrace *trace;
unsigned long int *frame_pointer;
__asm__
(
"movq %%rbp, %0\n"
: [frame_pointer] "=r"(frame_pointer)
);
if(LIBMPROF_SHARED_MEM->config.gnu)
frame_pointer = (unsigned long int*)(*frame_pointer);
trace = create_backtrace();
trace_(frame_pointer,trace,0);
return_address = *(frame_pointer + 1);
match_transaction_path.trace = trace;
compilation_unit = address_to_compilation_unit(return_address);
parent_function = address_to_function(return_address,compilation_unit);
if(LIBMPROF_SHARED_MEM->config.call_sites || parent_function == 0)
match_transaction_point.address = return_address;
else
match_transaction_point.address = parent_function->address;
match.address = (unsigned long int)ptr;
if(0 == (transaction_point = RB_FIND(TransactionPointTree,&TRANSACTION_POINTS,&match_transaction_point)))
{
transaction_point = create_transaction_point(TRANSACTION_TYPE_FREE,match_transaction_point.address);
transaction_path = create_transaction_path(TRANSACTION_TYPE_FREE,trace,transaction_point);
}
else if(0 == (transaction_path = RB_FIND(TransactionPathTree,&transaction_point->paths,&match_transaction_path)))
transaction_path = create_transaction_path(TRANSACTION_TYPE_FREE,trace,transaction_point);
RB_FOREACH(orig_transaction_point,TransactionPointTree,&TRANSACTION_POINTS)
{
RB_FOREACH(orig_transaction_path,TransactionPathTree,&orig_transaction_point->paths)
{
if((memory_block = RB_FIND(MemoryBlockTree,&orig_transaction_path->memory_blocks,&match)))
{
orig_transaction_path->current_num_transactions--;
orig_transaction_path->current_bytes_allocated -= memory_block->size;
transaction_path->total_num_frees++;
transaction_path->total_bytes_freed += memory_block->size;
RB_REMOVE(MemoryBlockTree,&orig_transaction_path->memory_blocks,memory_block);
LIBMPROF_TOTAL_BYTES_FREED += memory_block->size;
update_free_bins(memory_block->size);
update_memory_breakdowns_with_free(memory_block);
update_function_breakdowns_with_free(frame_pointer,memory_block);
free(memory_block);
}
}
}
LIBMPROF_NUM_FREES++;
free(trace);
free(ptr);
sem_post(MPROF_MEM_MUTEX);
}
__attribute__((destructor)) void libmprof_final()
{
fprintf(stderr,"\n[mprof] MEMORY STATISTICS\n");
memory_breakdown_table_out();
leak_table_out();
function_breakdown_table_out();
fprintf(stderr,"[mprof] Memory usage summary:\n");
fprintf(stderr,"[mprof] Program allocated %ld block(s)\n",LIBMPROF_TOTAL_NUM_TRANSACTIONS);
fprintf(stderr,"[mprof] (malloc: %ld, calloc: %ld, realloc: %ld)\n",LIBMPROF_NUM_MALLOCS,LIBMPROF_NUM_CALLOCS,LIBMPROF_NUM_REALLOCS);
fprintf(stderr,"[mprof] Program freed %ld block(s)\n",LIBMPROF_NUM_FREES);
if(0 == LIBMPROF_SHARED_MEM->config.output_to_stderr)
fprintf(stderr,"[mprof] For detailed memory usage statistics, consult the file \"%s\".\n",MPROF_OUTPUT_FILE_NAME);
shmdt(LIBMPROF_SHARED_MEM);
sem_unlink(MPROF_MEM_MUTEX_NAME);
fclose(MPROF_OUTPUT_FILE);
}
DwarfySourceRecord *address_to_source_record(unsigned long int address,DwarfyCompilationUnit *compilation_unit)
{
DwarfyObjectRecord match_location_record;
DwarfyObjectRecord *object_record;
DwarfySourceRecord *source_record;
Dl_info info;
if(compilation_unit == 0)
return 0;
match_location_record.address = address;
match_location_record.address = address;
object_record = RB_NFIND(DwarfyObjectRecordTree,&compilation_unit->line_numbers,&match_location_record);
source_record = LIST_FIRST(&object_record->source_records);
return source_record;
}
DwarfyFunction *address_to_function(unsigned long int address,DwarfyCompilationUnit *compilation_unit)
{
DwarfyFunction *function;
DwarfyFunction match_function;
if(compilation_unit == 0)
return 0;
function = 0;
match_function.address = address;
function = RB_NFIND(DwarfyFunctionTree,&compilation_unit->functions,&match_function);
return function;
}
void squash(char *st)
{
int z = 0;
while(st[z] != 0)
{
if(strlen(st + z) >= 3 && st[z] == '.' && st[z+1] == 's' && st[z+2] == 'o')
{
st[z+3] = 0;
break;
}
z++;
}
}
DwarfyCompilationUnit *address_to_compilation_unit(unsigned long int address)
{
DwarfyObjectRecord match_location_record;
DwarfyObjectRecord *nearest;
DwarfyCompilationUnit *compilation_unit;
DwarfyCompilationUnit *nearest_compilation_unit = 0;
SortedLibrary match_library,*library;
unsigned long int *nearest_address = (unsigned long int*)0xFFFFFFFFFFFFFFFF;
Dl_info info;
char buff[256];
int i = 0;
if(0 == dladdr((void*)address,&info))
return 0;
strcpy(buff,file_part(info.dli_fname));
squash(buff);
SortedLibrary *sl;
strcpy(match_library.name,buff);
if(0 == (sl = RB_FIND(SortedLibraryTree,&LIBMPROF_LIBS,&match_library)))
return 0;
if(sl->dwarf == 0)
return 0;
match_location_record.address = address;
RB_FOREACH(library,SortedLibraryTree,&LIBMPROF_LIBS)
{
if(library->dwarf)
{
LIST_FOREACH(compilation_unit,&library->dwarf->compilation_units,linkage)
{
nearest = RB_NFIND(DwarfyObjectRecordTree,&compilation_unit->line_numbers,&match_location_record);
if(nearest && ((void*)(address - nearest->address)) < ((void*)nearest_address))
{
nearest_address = ((void*)(address - nearest->address));
nearest_compilation_unit = compilation_unit;
}
}
}
}
return nearest_compilation_unit;
}
char *percentage_as_string(unsigned long int numerator,unsigned long int denominator,char *buffer)
{
double percentage;
if(denominator == 0)
{
strcpy(buffer,"0");
return buffer;
}
percentage = ((double)numerator) / ((double)denominator) * 100.0;
if(percentage - floor(percentage) < 0.5)
percentage = floor(percentage);
else
percentage = ceil(percentage);
sprintf(buffer,"%lu",(unsigned long int)percentage);
return buffer;
}
void memory_breakdown_table_out()
{
DwarfyCompilationUnit *compilation_unit;
DwarfyStruct *struct_;
MemoryBreakdown *memory_breakdown;
char percentage1_buff[4];
char percentage2_buff[4];
char *struct_list;
int struct_list_length;
int i;
fprintf(MPROF_OUTPUT_FILE,"[mprof] TABLE 1: ALLOCATION BINS\n\n");
fprintf(MPROF_OUTPUT_FILE,"%10s %10s %10s %4s %10s %10s %4s %s\n","size","allocs", "bytes","(%)","frees","kept","(%)"," types");
struct_list = malloc(1);
struct_list[0] = 0;
struct_list_length = 0;
RB_FOREACH(memory_breakdown,MemoryBreakdownTree,&MEMORY_BREAKDOWNS)
{
i = 0;
if(LIBMPROF_SHARED_MEM->config.structs)
{
while(strlen(LIBMPROF_SHARED_MEM->libraries[i].name))
{
if(LIBMPROF_SHARED_MEM->libraries[i].dwarf && strcmp(LIBMPROF_SHARED_MEM->libraries[i].name,"libmprof.so"))
{
LIST_FOREACH(compilation_unit,&LIBMPROF_SHARED_MEM->libraries[i].dwarf->compilation_units,linkage)
{
RB_FOREACH(struct_,DwarfyStructTree,&compilation_unit->structs)
{
if(struct_->size == memory_breakdown->size)
{
if(struct_list_length > 0)
strcat(struct_list,", ");
if(strlen(struct_list) + strlen(struct_->name) + 3 > struct_list_length)
{
struct_list = realloc(struct_list,struct_list_length + 256);
struct_list_length += 256;
}
strcat(struct_list,struct_->name);
}
}
}
}
i++;
}
}
fprintf(MPROF_OUTPUT_FILE,"%10lu %10lu %10lu %4s %10lu %10lu %4s %s\n",
memory_breakdown->size,
memory_breakdown->total_num_allocs,
memory_breakdown->total_bytes_allocated,
percentage_as_string(memory_breakdown->total_bytes_allocated,LIBMPROF_TOTAL_BYTES_ALLOCATED,percentage1_buff),
memory_breakdown->total_num_frees,
memory_breakdown->current_bytes_allocated,
percentage_as_string(memory_breakdown->total_bytes_allocated,LIBMPROF_TOTAL_BYTES_ALLOCATED - LIBMPROF_TOTAL_BYTES_FREED,percentage2_buff),
struct_list);
struct_list = realloc(struct_list,1);
struct_list[0] = 0;
struct_list_length = 0;
}
fprintf(MPROF_OUTPUT_FILE,"\n");
}
void function_breakdown_table_out()
{
FunctionBreakdown *function_breakdown;
char percentage1_buff[4];
char percentage2_buff[4];
char percentage3_buff[4];
char percentage4_buff[4];
char alloc_size_breakdown[32];
char leak_size_breakdown[32];
fprintf(MPROF_OUTPUT_FILE,"[mprof] TABLE 3: DIRECT_ALLOCATION\n\n");
fprintf(MPROF_OUTPUT_FILE,"%12s %12s %16s %12s %16s %12s %s\n","% mem","bytes","% mem(size)","bytes kept","% all kept","calls"," name");
fprintf(MPROF_OUTPUT_FILE," s m l x s m l x\n");
RB_FOREACH(function_breakdown,FunctionBreakdownTree,&FUNCTION_BREAKDOWNS)
{
sprintf(alloc_size_breakdown,"%4s%4s%4s%4s",
percentage_as_string(function_breakdown->num_allocations_small,LIBMPROF_NUM_ALLOCATIONS_SMALL,percentage1_buff),
percentage_as_string(function_breakdown->num_allocations_medium,LIBMPROF_NUM_ALLOCATIONS_MEDIUM,percentage2_buff),
percentage_as_string(function_breakdown->num_allocations_large,LIBMPROF_NUM_ALLOCATIONS_LARGE,percentage3_buff),
percentage_as_string(function_breakdown->num_allocations_xlarge,LIBMPROF_NUM_ALLOCATIONS_XLARGE,percentage4_buff));
sprintf(leak_size_breakdown,"%4s%4s%4s%4s",
percentage_as_string(function_breakdown->num_allocations_small - function_breakdown->num_frees_small,LIBMPROF_NUM_ALLOCATIONS_SMALL - LIBMPROF_NUM_FREES_SMALL,percentage1_buff),
percentage_as_string(function_breakdown->num_allocations_medium - function_breakdown->num_frees_medium,LIBMPROF_NUM_ALLOCATIONS_MEDIUM - LIBMPROF_NUM_FREES_MEDIUM,percentage2_buff),
percentage_as_string(function_breakdown->num_allocations_large - function_breakdown->num_frees_large,LIBMPROF_NUM_ALLOCATIONS_LARGE - LIBMPROF_NUM_FREES_LARGE,percentage3_buff),
percentage_as_string(function_breakdown->num_allocations_xlarge - function_breakdown->num_frees_xlarge,LIBMPROF_NUM_ALLOCATIONS_XLARGE - LIBMPROF_NUM_FREES_XLARGE,percentage4_buff));
fprintf(MPROF_OUTPUT_FILE,"%12s %12lu %16s %12lu %16s %12lu %s()\n",
percentage_as_string(function_breakdown->total_bytes_allocated,LIBMPROF_TOTAL_BYTES_ALLOCATED,percentage1_buff),
function_breakdown->total_bytes_allocated,
alloc_size_breakdown,
function_breakdown->current_bytes_allocated,
leak_size_breakdown,
function_breakdown->num_calls,
function_breakdown->name);
}
fprintf(MPROF_OUTPUT_FILE,"\n");
}
void leak_table_out()
{
TransactionPoint *transaction_point;
TransactionPath *transaction_path;
TransactionPathSorted *transaction_path_sorted;
char path[512];
char percentage1_buff[4];
char percentage2_buff[4];
char percentage3_buff[4];
int i;
TransactionPathSortedTree_t sorted_alloc_tree;
TransactionPathSortedTree_t sorted_free_tree;
TransactionPathSortedTree_t sorted_generic_tree;
TransactionPathSorted *sorted;
fprintf(MPROF_OUTPUT_FILE,"[mprof] TABLE 2: MEMORY LEAKS\n\n");
fprintf(MPROF_OUTPUT_FILE,"%10s %4s%10s%10s %4s%10s%10s %4s %s\n","kept bytes", "(%)","allocs", "bytes", "(%)","frees", "bytes", "(%)", "path");
RB_INIT(&sorted_generic_tree);
RB_FOREACH(transaction_point,TransactionPointTree,&TRANSACTION_POINTS)
{
RB_FOREACH(transaction_path,TransactionPathTree,&transaction_point->paths)
{
if(transaction_path->current_bytes_allocated || (LIBMPROF_SHARED_MEM->config.call_sites && transaction_path->total_bytes_freed))
{
sorted = malloc(sizeof(TransactionPathSorted));
memcpy(sorted,transaction_path,sizeof(TransactionPath));
RB_INSERT(TransactionPathSortedTree,&sorted_generic_tree,sorted);
}
}
}
RB_FOREACH(transaction_path_sorted,TransactionPathSortedTree,&sorted_generic_tree)
{
path[0] = 0;
if(transaction_path_sorted->trace->too_deep)
strcat(path,"... ");
for(i = MPROF_TRACE_DEPTH - 1; i >= 0; i--)
{
if(transaction_path_sorted->trace->function_names[i][0])
{
strcat(path,transaction_path_sorted->trace->function_names[i]);
if(i)
strcat(path," -> ");
}
}
fprintf(MPROF_OUTPUT_FILE,"%10lu %4s%10lu%10lu %4s%10lu%10lu %4s %s\n",
transaction_path_sorted->current_bytes_allocated,
percentage_as_string(transaction_path_sorted->current_bytes_allocated,LIBMPROF_TOTAL_BYTES_ALLOCATED - LIBMPROF_TOTAL_BYTES_FREED,percentage1_buff),
transaction_path_sorted->total_num_transactions,
transaction_path_sorted->total_bytes_allocated,
percentage_as_string(transaction_path_sorted->total_bytes_allocated,LIBMPROF_TOTAL_BYTES_ALLOCATED,percentage2_buff),
transaction_path_sorted->total_num_frees,
transaction_path_sorted->total_bytes_freed,
percentage_as_string(transaction_path_sorted->total_bytes_freed,LIBMPROF_TOTAL_BYTES_FREED,percentage3_buff),
path);
}
fprintf(MPROF_OUTPUT_FILE,"\n");
}
|
SanctaMaria1997/mprof | elf_util.c | /*
BSD 2-Clause License
Copyright (c) 2019, SanctaMaria1997
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <elf.h>
#include "elf_util.h"
unsigned char *load_elf(char *file_name)
{
unsigned char *block;
unsigned int file_size;
FILE *f;
block = 0;
f = fopen(file_name,"rb");
if(f == 0)
return 0;
fseek(f,0,SEEK_END);
file_size = ftell(f);
fseek(f,0,SEEK_SET);
block = malloc(file_size);
fread(block,file_size,1,f);
fclose(f);
return block;
}
unsigned long int get_elf_base_address(unsigned char *elf)
{
char *section_name;
Elf64_Ehdr *elf_header;
Elf64_Phdr *program_header;
unsigned short num_program_headers;
unsigned long int lowest_address = 0xffffffffffffffff;
int i;
elf_header = (Elf64_Ehdr*)elf;
program_header = (Elf64_Phdr*)(elf + elf_header->e_phoff);
num_program_headers = elf_header->e_phnum;
for(i = 0; i < num_program_headers; i++)
{
if(program_header[i].p_type == PT_LOAD && program_header[i].p_vaddr < lowest_address)
lowest_address = program_header[i].p_vaddr;
}
return lowest_address;
}
unsigned long int get_elf_symbol(unsigned char *elf,char *name)
{
char *section_name;
Elf64_Ehdr *elf_header;
Elf64_Shdr *section_header;
Elf64_Sym *symbol;
unsigned long int num_sections;
unsigned long int section_header_size;
unsigned long int section_names_index;
unsigned long int symtab_offset;
unsigned long int symtab_size;
unsigned long int strtab_offset;
unsigned long int strtab_size;
unsigned long int address;
int i;
address = 0;
elf_header = (Elf64_Ehdr*)elf;
section_header = (Elf64_Shdr*)(elf + elf_header->e_shoff);
num_sections = elf_header->e_shnum;
section_header_size = elf_header->e_shentsize;
section_names_index = elf_header->e_shstrndx;
if(section_names_index == SHN_XINDEX)
section_names_index = section_header->sh_link;
for(i = 0; i < num_sections; i++)
{
section_name = (char*)(elf + section_header[section_names_index].sh_offset + section_header[i].sh_name);
if(!strcmp(section_name,".symtab"))
{
symtab_offset = section_header[i].sh_offset;
symtab_size = section_header[i].sh_size;
}
else if(!strcmp(section_name,".strtab"))
{
strtab_offset = section_header[i].sh_offset;
strtab_size = section_header[i].sh_size;
}
}
symbol = (Elf64_Sym*)(elf + symtab_offset);
while(((unsigned char*)symbol) < elf + symtab_offset + symtab_size)
{
if(!strcmp(name,(const char*)(elf + strtab_offset + symbol->st_name)))
{
address = symbol->st_value;
break;
}
symbol++;
}
return address;
}
unsigned long int get_elf_relocation(unsigned char *elf,char *name)
{
char *section_name;
Elf64_Ehdr *elf_header;
Elf64_Shdr *section_header;
Elf64_Sym *symbol;
unsigned long int num_sections;
unsigned long int section_header_size;
unsigned long int section_names_index;
unsigned long int dynsym_offset;
unsigned long int dynsym_size;
unsigned long int dynstr_offset;
unsigned long int dynstr_size;
unsigned long int rela_offset;
unsigned long int rela_size;
int success = 0;
elf_header = (Elf64_Ehdr*)elf;
section_header = (Elf64_Shdr*)(elf + elf_header->e_shoff);
num_sections = elf_header->e_shnum;
section_header_size = elf_header->e_shentsize;
section_names_index = elf_header->e_shstrndx;
if(section_names_index == SHN_XINDEX)
section_names_index = section_header->sh_link;
int i;
int m;
for(i = 0; i < num_sections; i++)
{
section_name = (char*)(elf + section_header[section_names_index].sh_offset + section_header[i].sh_name);
if(!strcmp(section_name,".dynsym"))
{
dynsym_offset = section_header[i].sh_offset;
dynsym_size = section_header[i].sh_size;
}
else if(!strcmp(section_name,".dynstr"))
{
dynstr_offset = section_header[i].sh_offset;
dynstr_size = section_header[i].sh_size;
}
else if(!strcmp(section_name,".rela.plt"))
{
rela_offset = section_header[i].sh_offset;
rela_size = section_header[i].sh_size;
}
}
Elf64_Rela *relocation = (Elf64_Rela*)(elf + rela_offset);
char *symbol_name;
while(((unsigned char*)relocation) < elf + rela_offset + rela_size)
{
symbol = ((Elf64_Sym*)(elf + dynsym_offset)) + ELF64_R_SYM(relocation->r_info);
symbol_name = (char*)(elf + dynstr_offset + symbol->st_name);
if(!strcmp(symbol_name,name))
{
success = 1;
break;
}
relocation++;
}
if(success)
{
return relocation->r_offset;
}
else
return 0;
}
|
SanctaMaria1997/mprof | dugong.c | #include <stdio.h>
#include <stdlib.h>
void dugong()
{
void *p;
p = malloc(123);
puts("Hi from dugong!");
p = malloc(321);
}
|
SanctaMaria1997/mprof | dwarfy.c | /*
BSD 2-Clause License
Copyright (c) 2019, SanctaMaria1997
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <elf.h>
#ifdef LINUX
#include <libdwarf/dwarf.h>
#elif defined(FREEBSD)
#include <dwarf.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "elf_util.h"
#include "dwarfy.h"
#ifdef FREEBSD
#define DW_LNE_set_discriminator 4
#endif
int DWARFY_FORMAT;
unsigned long int DEBUG_INFO_SIZE;
unsigned long int COMPILATION_UNIT_OFFSET;
unsigned long int COMPILATION_UNIT_LENGTH;
unsigned int LINE_NUMBER_PROGRAM_OFFSET;
unsigned char *DEBUG_INFO,*DEBUG_ABBREV,*DEBUG_LINE,*DEBUG_STR,*DEBUG_ARANGES;
unsigned long int DWARFY_ELF_BASE_ADDRESS;
unsigned long int DWARFY_ELF_RUNTIME_ADDRESS;
int dwarfy_compare_object_records_by_address(DwarfyObjectRecord *dlr1,DwarfyObjectRecord *dlr2)
{
return dlr2->address - dlr1->address;
}
int dwarfy_compare_abbreviations(DwarfyAbbreviation *a1,DwarfyAbbreviation *a2)
{
return a2->code - a1->code;
}
int dwarfy_compare_functions(DwarfyFunction *df1,DwarfyFunction *df2)
{
return df2->address - df1->address;
}
int dwarfy_compare_structs(DwarfyStruct *ds1,DwarfyStruct *ds2)
{
return strcmp(ds1->name,ds2->name);
}
int dwarfy_compare_source_code(DwarfySourceCode *dsc1,DwarfySourceCode *dsc2)
{
return strcmp(dsc2->file_name,dsc1->file_name);
}
RB_GENERATE(DwarfyObjectRecordTree,DwarfyObjectRecord,DwarfyObjectRecordLinks,dwarfy_compare_object_records_by_address)
RB_GENERATE(DwarfyFunctionTree,DwarfyFunction,DwarfyFunctionLinks,dwarfy_compare_functions)
RB_GENERATE(DwarfyStructTree,DwarfyStruct,DwarfyStructLinks,dwarfy_compare_structs)
RB_GENERATE(DwarfyAbbreviationTree,DwarfyAbbreviation,DwarfyAbbreviationLinks,dwarfy_compare_abbreviations)
RB_GENERATE(DwarfySourceCodeTree,DwarfySourceCode,DwarfySourceCodeLinks,dwarfy_compare_source_code);
DWARF_DATA *load_dwarf(char *file_name,unsigned long int runtime_address)
{
char debug_file_name[256];
unsigned char *elf;
unsigned char *elf_standalone_debug;
DWARF_DATA *debug_info;
elf = 0;
elf_standalone_debug = 0;
if(0 == (elf = load_elf(file_name)))
return 0;
DWARFY_ELF_BASE_ADDRESS = get_elf_base_address(elf);
DWARFY_ELF_RUNTIME_ADDRESS = runtime_address;
if(0 == (debug_info = dwarfy_load_debug_info(elf)))
{
strcpy(debug_file_name,file_name);
strcat(debug_file_name,".debug");
if(0 == (elf_standalone_debug = load_elf(debug_file_name)))
{
debug_info = 0;
goto cleanup;
}
debug_info = dwarfy_load_debug_info(elf_standalone_debug);
}
cleanup:
if(elf)
free(elf);
if(elf_standalone_debug)
free(elf_standalone_debug);
return debug_info;
}
DWARF_DATA *dwarfy_load_debug_info(unsigned char *elf)
{
int result;
char *section_name;
char debug_file_name[256];
Elf64_Ehdr *elf_header;
Elf64_Phdr *program_header;
unsigned short num_program_headers;
Elf64_Shdr *section_header;
unsigned int num_sections;
unsigned int section_header_size;
unsigned int section_names_index;
DEBUG_INFO = DEBUG_ABBREV = DEBUG_LINE = DEBUG_STR = 0;
DEBUG_INFO_SIZE = 0;
COMPILATION_UNIT_OFFSET = 0;
COMPILATION_UNIT_LENGTH = 0;
LINE_NUMBER_PROGRAM_OFFSET = 0;
elf_header = (Elf64_Ehdr*)elf;
program_header = (Elf64_Phdr*)(elf + elf_header->e_phoff);
num_program_headers = elf_header->e_phnum;
section_header = (Elf64_Shdr*)(elf + elf_header->e_shoff);
num_sections = elf_header->e_shnum;
section_header_size = elf_header->e_shentsize;
section_names_index = elf_header->e_shstrndx;
if(section_names_index == SHN_XINDEX)
section_names_index = section_header->sh_link;
int i;
int m;
for(i = 0; i < num_sections; i++)
{
section_name = (char*)(elf + section_header[section_names_index].sh_offset + section_header[i].sh_name);
if(!strcmp(section_name,".debug_info"))
{
DEBUG_INFO = elf + section_header[i].sh_offset;
DEBUG_INFO_SIZE = (unsigned long int)section_header[i].sh_size;
}
if(!strcmp(section_name,".debug_abbrev"))
DEBUG_ABBREV = elf + section_header[i].sh_offset;
if(!strcmp(section_name,".debug_line"))
DEBUG_LINE = elf + section_header[i].sh_offset;
if(!strcmp(section_name,".debug_str"))
DEBUG_STR = elf + section_header[i].sh_offset;
}
if(0 == (DEBUG_INFO && DEBUG_ABBREV && DEBUG_LINE && DEBUG_STR))
return 0;
return dwarfy_main();
}
DwarfyCompilationUnit *create_compilation_unit()
{
DwarfyCompilationUnit *compilation_unit;
compilation_unit = malloc(sizeof(DwarfyCompilationUnit));
RB_INIT(&compilation_unit->line_numbers);
RB_INIT(&compilation_unit->addresses);
RB_INIT(&compilation_unit->functions);
RB_INIT(&compilation_unit->structs);
compilation_unit->num_include_paths = 1;
compilation_unit->include_paths[0] = "";
compilation_unit->num_file_names = 0;
RB_INIT(&compilation_unit->abbreviations);
LIST_INIT(&compilation_unit->DIE_list);
RB_INIT(&compilation_unit->source_code);
return compilation_unit;
}
DWARF_DATA *dwarfy_main()
{
DWARF_DATA *elf;
unsigned char *address;
elf = malloc(sizeof(DWARF_DATA));
LIST_INIT(&elf->compilation_units);
dwarfy_consume_compilation_units(&elf->compilation_units,&address);
return elf;
}
void dwarfy_consume_compilation_units(DwarfyCompilationUnitList_t *compilation_units,unsigned char **address)
{
DwarfyCompilationUnitHeader *compilation_unit_header;
DwarfyCompilationUnit *compilation_unit;
unsigned char *line_number_program_ptr;
unsigned char *abbreviations_ptr;
unsigned int unit_length;
short unsigned int version;
unsigned int debug_abbrev_offset;
unsigned char architecture_address_size;
*address = DEBUG_INFO;
while((*address = DEBUG_INFO + COMPILATION_UNIT_LENGTH) < DEBUG_INFO + DEBUG_INFO_SIZE)
{
compilation_unit = create_compilation_unit();
compilation_unit_header = (DwarfyCompilationUnitHeader*)(*address);
abbreviations_ptr = DEBUG_ABBREV + compilation_unit_header->abbreviations_offset;
dwarfy_consume_abbreviations(compilation_unit,&abbreviations_ptr);
COMPILATION_UNIT_LENGTH += compilation_unit_header->unit_length + 4;
*address += sizeof(DwarfyCompilationUnitHeader);
dwarfy_consume_DIEs(&compilation_unit->DIE_list,compilation_unit,address);
line_number_program_ptr = DEBUG_LINE + LINE_NUMBER_PROGRAM_OFFSET;
dwarfy_consume_line_numbers(compilation_unit,&line_number_program_ptr);
//dwarfy_load_source_code(compilation_unit);
LIST_INSERT_HEAD(compilation_units,compilation_unit,linkage);
}
}
void dwarfy_consume_DIEs(DwarfyDIEList_t *DIE_list,DwarfyCompilationUnit *compilation_unit,unsigned char **address)
{
DwarfyDIE *DIE;
DwarfyAbbreviation *abbreviation;
DwarfyAbbreviation match;
DwarfyAttributeSpecList_t *attribute_spec_list;
DwarfyAttributeSpec *spec;
DwarfyFunction *function;
DwarfyStruct *struct_;
unsigned long int abbreviation_code;
unsigned long int size;
int z = 1;
function = 0;
unsigned long int function_address;
int DIE_is_function;
char function_name[256];
int DIE_is_struct;
char struct_name[256];
unsigned long int struct_size;
unsigned short language_code;
for(;;)
{
if(0 == (abbreviation_code = dwarfy_consume_unsigned_LEB128(address)))
return;
if(*address - DEBUG_INFO >= COMPILATION_UNIT_LENGTH)
return;
DIE = malloc(sizeof(DwarfyDIE));
DIE->abbreviation_code = abbreviation_code;
LIST_INIT(&DIE->children);
match.code = abbreviation_code;
abbreviation = RB_FIND(DwarfyAbbreviationTree,&compilation_unit->abbreviations,&match);
spec = LIST_FIRST(&abbreviation->specs);
DIE_is_function = 0;
function_address = 0;
DIE_is_struct = 0;
while(spec)
{
if(abbreviation->tag == DW_TAG_subprogram)
{
DIE_is_function = 1;
if(spec->name == DW_AT_low_pc)
{function_address = (**((unsigned long int**)address)) - DWARFY_ELF_BASE_ADDRESS + DWARFY_ELF_RUNTIME_ADDRESS;
}
else if(spec->name == DW_AT_name)
{
if(spec->form == DW_FORM_strp)
strcpy(function_name,((char*)DEBUG_STR) + **((unsigned int**)address));
else
strcpy(function_name,(char*)*address);
}
}
else if(abbreviation->tag == DW_TAG_compile_unit)
{
if(spec->name == DW_AT_stmt_list)
{
LINE_NUMBER_PROGRAM_OFFSET = **((unsigned int**)address);
}
else if(spec->name == DW_AT_language)
{
language_code = **((unsigned char**)address);
if(language_code != DW_LANG_C99 && language_code != DW_LANG_C89 && language_code != DW_LANG_C)
{
fprintf(stderr,"[mprof] DWARF error: module was not written in C99, C89, or C.\n");
exit(1);
}
}
}
else if(abbreviation->tag == DW_TAG_structure_type)
{
DIE_is_struct = 1;
if(spec->name == DW_AT_byte_size)
{
switch(spec->form)
{
case DW_FORM_data1:
{
struct_size = **((unsigned char**)address);
break;
}
case DW_FORM_data2:
{
struct_size = **((unsigned short**)address);
break;
}
case DW_FORM_data4:
{
struct_size = **((unsigned int**)address);
break;
}
case DW_FORM_data8:
{
struct_size = **((unsigned long int**)address);
break;
}
}
}
else if(spec->name == DW_AT_name)
{
if(spec->form == DW_FORM_strp)
strcpy(struct_name,((char*)DEBUG_STR) + **((unsigned int**)address));
else
strcpy(struct_name,(char*)*address);
}
}
switch(spec->form)
{
case DW_FORM_data1:
{
(*address)++;
break;
}
case DW_FORM_data2:
{
(*address) += 2;
break;
}
case DW_FORM_data4:
{
(*address) += 4;
break;
}
case DW_FORM_data8:
{
(*address) += 8;
break;
}
case DW_FORM_sdata:
{
dwarfy_consume_signed_LEB128((unsigned char**)address);
break;
}
case DW_FORM_udata:
{
dwarfy_consume_unsigned_LEB128(address);
break;
}
case DW_FORM_ref1:
{
(*address)++;
break;
}
case DW_FORM_ref2:
{
(*address) += 2;
break;
}
case DW_FORM_ref4:
{
(*address) += 4;
break;
}
case DW_FORM_ref8:
{
(*address) += 8;
break;
}
case DW_FORM_flag:
{
(*address)++;
break;
}
case DW_FORM_flag_present:
{
break;
}
case DW_FORM_addr:
{
(*address) += 8;
break;
}
case DW_FORM_sec_offset:
{
(*address) += 4;
break;
}
case DW_FORM_strp:
{
(*address) += 4;
break;
}
case DW_FORM_string:
{
(*address) += strlen((char*)*address) + 1;
break;
}
case DW_FORM_exprloc:
{
size = dwarfy_consume_unsigned_LEB128(address);
(*address) += size;
break;
}
case DW_FORM_block1:
{
size = **address;
(*address) += size + 1;
break;
}
default:
{
exit(1);
}
}
spec = LIST_NEXT(spec,linkage);
}
if(DIE_is_function && function_address)
{
function = malloc(sizeof(DwarfyFunction));
function->address = function_address;
function->name = malloc(256);
strcpy(function->name,function_name);
if(!strcmp(function_name,"main"))
compilation_unit->has_main_function = 1;
RB_INSERT(DwarfyFunctionTree,&compilation_unit->functions,function);
}
else if(DIE_is_struct)
{
struct_ = malloc(sizeof(DwarfyStruct));
struct_->size = struct_size;
struct_->name = malloc(256);
strcpy(struct_->name,struct_name);
RB_INSERT(DwarfyStructTree,&compilation_unit->structs,struct_);
}
function = 0;
function_address = 0;
DIE_is_function = 0;
function_name[0] = 0;
struct_ = 0;
DIE_is_struct = 0;
struct_name[0] = 0;
if(abbreviation->has_children)
dwarfy_consume_DIEs(&DIE->children,compilation_unit,address);
LIST_INSERT_HEAD(DIE_list,DIE,linkage);
}
}
void dwarfy_consume_abbreviations(DwarfyCompilationUnit *compilation_unit,unsigned char **address)
{
DwarfyAbbreviation *abbreviation;
while((abbreviation = dwarfy_consume_abbreviation_header(address)))
{
dwarfy_consume_abbreviation_attribute_specs(abbreviation,address);
RB_INSERT(DwarfyAbbreviationTree,&compilation_unit->abbreviations,abbreviation);
}
}
DwarfyAbbreviation *dwarfy_consume_abbreviation_header(unsigned char **address)
{
DwarfyAbbreviation *abbreviation;
unsigned long int abbreviation_code;
unsigned long int tag;
abbreviation_code = dwarfy_consume_unsigned_LEB128(address);
if(abbreviation_code == 0)
return 0;
abbreviation = malloc(sizeof(DwarfyAbbreviation));
abbreviation->code = abbreviation_code;
tag = dwarfy_consume_unsigned_LEB128(address);
abbreviation->tag = tag;
if(**address == DW_CHILDREN_yes)
{
abbreviation->has_children = 1;
}
else if(**address == DW_CHILDREN_no)
{
abbreviation->has_children = 0;
}
abbreviation->num_items = 0;
(*address)++;
return abbreviation;
}
void dwarfy_consume_abbreviation_attribute_specs(DwarfyAbbreviation *abbreviation,unsigned char **address)
{
unsigned long int attribute_name, attribute_form;
DwarfyAttributeSpec *spec;
DwarfyAttributeSpec *tail;
tail = 0;
LIST_INIT(&abbreviation->specs);
for(;;)
{
attribute_name = dwarfy_consume_unsigned_LEB128(address);
attribute_form = dwarfy_consume_unsigned_LEB128(address);
if(attribute_name == 0 && attribute_form == 0)
return;
spec = malloc(sizeof(DwarfyAttributeSpec));
spec->name = attribute_name;
spec->form = attribute_form;
if(LIST_EMPTY(&abbreviation->specs))
LIST_INSERT_HEAD(&abbreviation->specs,spec,linkage);
else
LIST_INSERT_AFTER(tail,spec,linkage);
tail = spec;
abbreviation->num_items++;
}
}
void dwarfy_consume_line_numbers(DwarfyCompilationUnit *compilation_unit,unsigned char **address)
{
DwarfyLineNumberHeader *line_number_header;
char is_stmt;
line_number_header = dwarfy_consume_line_number_header(compilation_unit,address);
dwarfy_execute_line_number_program(compilation_unit,line_number_header,address);
return;
}
DwarfyLineNumberHeader *dwarfy_consume_line_number_header(DwarfyCompilationUnit *compilation_unit,unsigned char **address)
{
DwarfyLineNumberHeader *line_number_header, *result;
char *string;
unsigned char *instruction_pointer;
unsigned long int index,modification,length;
line_number_header = (DwarfyLineNumberHeader*)*address;
*address = ((unsigned char*)(line_number_header + 1)) + 12;
while(**address != '\0')
{
compilation_unit->num_include_paths++;
compilation_unit->include_paths[compilation_unit->num_include_paths - 1] = malloc(strlen((char*)(*address)) + 1);
strcpy(compilation_unit->include_paths[compilation_unit->num_include_paths - 1],(char*)(*address));
*address += strlen((char*)(*address)) + 1;
}
(*address)++;
while(**address != '\0')
{
compilation_unit->num_file_names++;
compilation_unit->file_names[compilation_unit->num_file_names - 1] = malloc(strlen((char*)(*address)) + 1);
strcpy(compilation_unit->file_names[compilation_unit->num_file_names - 1],(char*)(*address));
*address += strlen((char*)(*address)) + 1;
index = dwarfy_consume_unsigned_LEB128(address);
compilation_unit->directory_indices[compilation_unit->num_file_names - 1] = index;
modification = dwarfy_consume_unsigned_LEB128(address);
length = dwarfy_consume_unsigned_LEB128(address);
}
(*address)++;
instruction_pointer = ((unsigned char*)(&line_number_header->minimum_instruction_length)) + line_number_header->header_length;
result = malloc(sizeof(DwarfyLineNumberHeader));
memcpy(result,line_number_header,sizeof(DwarfyLineNumberHeader));
return result;
}
void dwarfy_init_line_number_state_machine(DwarfyLineNumberStateMachine *state_machine,DwarfyLineNumberHeader* line_number_header)
{
state_machine->address = 0;
state_machine->file = 1;
state_machine->line = 1;
state_machine->column = 0;
state_machine->is_stmt = line_number_header->default_is_stmt;
state_machine->basic_block = 0;
state_machine->end_sequence = 0;
}
void dwarfy_execute_line_number_program(DwarfyCompilationUnit *compilation_unit,DwarfyLineNumberHeader *line_number_header,unsigned char **address)
{
unsigned char opcode;
unsigned char adjusted_opcode;
unsigned long int operation_size;
char *file_name;
unsigned long int directory_index;
unsigned long int modification_time;
unsigned long int size;
DwarfyLineNumberStateMachine state_machine;
dwarfy_init_line_number_state_machine(&state_machine,line_number_header);
for(;;)
{
opcode = **address;
(*address)++;
if(opcode == 0)
{
// extended opcode
dwarfy_consume_unsigned_LEB128(address);
opcode = **address;
(*address)++;
switch(opcode)
{
case DW_LNE_end_sequence:
state_machine.end_sequence = 1;
dwarfy_line_number_state_machine_out(&state_machine,compilation_unit);
return;
case DW_LNE_set_address:
state_machine.address = **((unsigned long int**)address);
(*address) += DWARFY_ARCHITECTURE_ADDRESS_SIZE ;
break;
case DW_LNE_define_file:
{
file_name = (char*)*address;
*address += strlen((char*)(*address)) + 1;
directory_index = dwarfy_consume_unsigned_LEB128(address);
modification_time = dwarfy_consume_unsigned_LEB128(address);
size = dwarfy_consume_unsigned_LEB128(address);
break;
}
case DW_LNE_set_discriminator:
dwarfy_consume_unsigned_LEB128(address);
break;
}
}
else if(opcode < line_number_header->opcode_base) // standard opcode
{
switch(opcode)
{
case DW_LNS_copy:
dwarfy_line_number_state_machine_out(&state_machine,compilation_unit);
state_machine.basic_block = 0;
break;
case DW_LNS_advance_pc:
state_machine.address += dwarfy_consume_unsigned_LEB128(address);
break;
case DW_LNS_advance_line:
{
state_machine.line += dwarfy_consume_signed_LEB128(address);
break;
}
case DW_LNS_set_file:
{
state_machine.file = dwarfy_consume_unsigned_LEB128(address);
break;
}
case DW_LNS_set_column:
state_machine.column = dwarfy_consume_unsigned_LEB128(address);
break;
case DW_LNS_negate_stmt:
state_machine.is_stmt = !state_machine.is_stmt;
break;
case DW_LNS_set_basic_block:
state_machine.basic_block = 1;
break;
case DW_LNS_const_add_pc:
adjusted_opcode = 255 - line_number_header->opcode_base;
state_machine.address += adjusted_opcode / line_number_header->line_range;
dwarfy_line_number_state_machine_out(&state_machine,compilation_unit);
break;
case DW_LNS_fixed_advance_pc:
state_machine.address += *((unsigned short*)(*address));
(*address) += 2;
break;
}
}
else // special opcode
{
adjusted_opcode = opcode - line_number_header->opcode_base;
state_machine.address += adjusted_opcode / line_number_header->line_range;
state_machine.line += line_number_header->line_base + (adjusted_opcode % line_number_header->line_range);
dwarfy_line_number_state_machine_out(&state_machine,compilation_unit);
}
}
}
void dwarfy_line_number_state_machine_out(DwarfyLineNumberStateMachine *state_machine,DwarfyCompilationUnit *compilation_unit)
{
DwarfyObjectRecord *object_record;
DwarfyObjectRecord match_object_record;
DwarfySourceRecord *source_record;
match_object_record.address = state_machine->address - DWARFY_ELF_BASE_ADDRESS + DWARFY_ELF_RUNTIME_ADDRESS;
if(0 == (object_record = RB_FIND(DwarfyObjectRecordTree,&compilation_unit->line_numbers,&match_object_record)))
{
object_record = malloc(sizeof(DwarfyObjectRecord));
LIST_INIT(&object_record->source_records);
object_record->address = state_machine->address - DWARFY_ELF_BASE_ADDRESS + DWARFY_ELF_RUNTIME_ADDRESS;
RB_INSERT(DwarfyObjectRecordTree,&compilation_unit->line_numbers,object_record);
}
source_record = malloc(sizeof(DwarfySourceRecord));
source_record->file = state_machine->file;
source_record->line_number = state_machine->line;
source_record->column = state_machine->column;
LIST_INSERT_HEAD(&object_record->source_records,source_record,linkage);
}
int file_num_lines(char *file_name)
{
FILE *file;
int file_size;
char *block;
int num_lines;
int i;
i = 0;
num_lines = 0;
file = fopen(file_name,"rb");
if(file == 0)
return 0;
fseek(file,0,SEEK_END);
file_size = ftell(file);
fseek(file,0,SEEK_SET);
block = malloc(file_size);
fread(block,file_size,1,file);
while(i < file_size)
{
if(block[i] == 0xA)
num_lines++;
i++;
}
fclose(file);
free(block);
return num_lines;
}
void dwarfy_load_source_code(DwarfyCompilationUnit *compilation_unit)
{
DwarfySourceCode *source_code;
char *source_line;
unsigned int line_number;
int i,j,k;
int num_lines;
char buffer[1024];
FILE *file;
unsigned long int file_size;
char *block;
for(i = 0; i < compilation_unit->num_file_names; i++)
{
strncpy(buffer,compilation_unit->include_paths[compilation_unit->directory_indices[i]],512);
strncat(buffer,compilation_unit->file_names[i],511);
num_lines = file_num_lines(buffer);
file = fopen(buffer,"rb");
if(!file)
continue;
source_code = malloc(sizeof(DwarfySourceCode));
source_code->file_name = malloc(strlen(compilation_unit->file_names[i]) + 1);
strcpy(source_code->file_name,compilation_unit->file_names[i]);
source_code->source_code = malloc(num_lines * sizeof(char*));
source_code->num_lines = num_lines;
fseek(file,0,SEEK_END);
file_size = ftell(file);
fseek(file,0,SEEK_SET);
block = malloc(file_size);
fread(block,file_size,1,file);
line_number = 0;
j = 0;
for(j = 0; j < file_size; j++)
{
line_number++;
k = j;
while(block[j] != 0xA && j < file_size)
j++;
source_line = malloc(j - k + 1);
memcpy(source_line,block + k,j-k);
source_line[j - k] = '\0';
source_code->source_code[line_number - 1] = source_line;
}
RB_INSERT(DwarfySourceCodeTree,&compilation_unit->source_code,source_code);
free(block);
fclose(file);
}
}
int dwarfy_compare_integers(unsigned long int a, unsigned long int b)
{
if(a < b)
return -1;
else if(a > b)
return 1;
else
return 0;
}
long int dwarfy_consume_signed_LEB128(unsigned char **address)
{
long int result = 0;
long int shift = 0;
long int size = DWARFY_ARCHITECTURE_ADDRESS_SIZE * 8;
unsigned long int byte = 0;
int i;
for(i = 0; 1; i++)
{
byte = (unsigned long int)((*address)[i]);
result |= ((byte & 0x7f) << shift);
shift += 7;
if ((byte & 0x80) == 0)
break;
}
if ((shift < size) && (byte & 0x40))
result |= - (1 << shift);
*address += i + 1;
return result;
}
unsigned long int dwarfy_consume_unsigned_LEB128(unsigned char **address)
{
unsigned long int result = 0;
unsigned long int shift = 0;
unsigned long int byte = 0;
int i;
for(i = 0; 1; i++)
{
byte = (unsigned long int)((*address)[i]);
result |= ((byte & 0x7F) << shift);
if ((byte & 0x80) == 0)
break;
shift += 7;
}
*address += i + 1;
return result;
}
char *dwarfy_tag_to_string(unsigned long int tag)
{
switch(tag)
{
case 0x01:
{
return "array_type";
}
case 0x02:
{
return "class_type";
}
case 0x03:
{
return "entry_point";
}
case 0x4:
{
return "enumeration_type";
}
case 0x05:
{
return "formal_parameter";
}
case 0x08:
{
return "imported_declaration";
}
case 0x0a:
{
return "label";
}
case 0x0b:
{
return "lexical_block";
}
case 0x0d:
{
return "member";
}
case 0x0f:
{
return "pointer_type";
}
case 0x10:
{
return "reference_type";
}
case 0x11:
{
return "compile_unit";
}
case 0x12:
{
return "string_type";
}
case 0x13:
{
return "structure_type";
}
case 0x15:
{
return "subroutine_type";
}
case 0x16:
{
return "typedef";
}
case 0x17:
{
return "union_type";
}
case 0x18:
{
return "unspecified_parameters";
}
case 0x19:
{
return "variant";
}
case 0x1a:
{
return "common_block";
}
case 0x1b:
{
return "common_inclusion";
}
case 0x1c:
{
return "inheritance";
}
case 0x1d:
{
return "inlined_subroutine";
}
case 0x1e:
{
return "module";
}
case 0x1f:
{
return "ptr_to_member_type";
}
case 0x20:
{
return "set_type";
}
case 0x21:
{
return "subrange_type";
}
case 0x22:
{
return "with_stmt";
}
case 0x23:
{
return "access_declaration";
}
case 0x24:
{
return "base_type";
}
case 0x25:
{
return "catch_block";
}
case 0x26:
{
return "const_type";
}
case 0x27:
{
return "constant";
}
case 0x28:
{
return "enumerator";
}
case 0x29:
{
return "file_type";
}
case 0x2a:
{
return "friend";
}
case 0x2b:
{
return "namelist";
}
case 0x2c:
{
return "namelist_item";
}
case 0x2d:
{
return "packed_type";
}
case 0x2e:
{
return "subprogram";
}
case 0x2f:
{
return "template_type_parameter";
}
case 0x30:
{
return "template_value_parameter";
}
case 0x31:
{
return "thrown_type";
}
case 0x32:
{
return "try_block";
}
case 0x33:
{
return "variant_part";
}
case 0x34:
{
return "variable";
}
case 0x35:
{
return "volatile_type";
}
case 0x36:
{
return "dwarf_procedure";
}
case 0x37:
{
return "restrict_type";
}
case 0x38:
{
return "interface_type";
}
case 0x39:
{
return "namespace";
}
case 0x3a:
{
return "imported_module";
}
case 0x3b:
{
return "unspecified_type";
}
case 0x3c:
{
return "partial_unit";
}
case 0x3d:
{
return "imported_unit";
}
case 0x3f:
{
return "condition";
}
case 0x40:
{
return "shared_type";
}
case 0x41:
{
return "type_unit";
}
case 0x42:
{
return "rvalue_reference_type";
}
case 0x43:
{
return "template_alias";
}
default:
{
if(tag >= 0x4080 && tag <= 0xffff)
return "USER_DEFINED_TAG";
else
return "UNKNOWN_TAG";
}
}
}
char *dwarfy_attribute_to_string(unsigned long int attribute)
{
switch(attribute)
{
case 0x01:
{
return "sibling";
}
case 0x02:
{
return "location";
}
case 0x03:
{
return "name";
}
case 0x09:
{
return "ordering";
}
case 0x0b:
{
return "byte_size";
}
case 0x0c:
{
return "bit_offset";
}
case 0x0d:
{
return "bit_size";
}
case 0x10:
{
return "stmt_list";
}
case 0x11:
{
return "low_pc";
}
case 0x12:
{
return "high_pc";
}
case 0x13:
{
return "language";
}
case 0x15:
{
return "discr";
}
case 0x16:
{
return "discr_value";
}
case 0x17:
{
return "visibility";
}
case 0x18:
{
return "import";
}
case 0x19:
{
return "string_length";
}
case 0x1a:
{
return "common_reference";
}
case 0x1b:
{
return "comp_dir";
}
case 0x1c:
{
return "const_value";
}
case 0x1d:
{
return "containing_type";
}
case 0x1e:
{
return "default_value";
}
case 0x20:
{
return "inline";
}
case 0x21:
{
return "is_optional";
}
case 0x22:
{
return "lower_bound";
}
case 0x25:
{
return "producer";
}
case 0x27:
{
return "prototyped";
}
case 0x2a:
{
return "return_addr";
}
case 0x2c:
{
return "start_scope";
}
case 0x2e:
{
return "bit_stride";
}
case 0x2f:
{
return "upper_bound";
}
case 0x31:
{
return "abstract_origin";
}
case 0x32:
{
return "accesibility";
}
case 0x33:
{
return "address_class";
}
case 0x34:
{
return "artificial";
}
case 0x35:
{
return "base_types";
}
case 0x36:
{
return "calling_convention";
}
case 0x37:
{
return "count";
}
case 0x38:
{
return "data_member_location";
}
case 0x39:
{
return "decl_column";
}
case 0x3a:
{
return "decl_file";
}
case 0x3b:
{
return "decl_line";
}
case 0x3c:
{
return "declaration";
}
case 0x3d:
{
return "discr_list";
}
case 0x3e:
{
return "encoding";
}
case 0x3f:
{
return "external";
}
case 0x40:
{
return "frame_base";
}
case 0x41:
{
return "friend";
}
case 0x42:
{
return "identifier_case";
}
case 0x43:
{
return "macro_info";
}
case 0x44:
{
return "namelist_item";
}
case 0x45:
{
return "priority";
}
case 0x46:
{
return "segment";
}
case 0x47:
{
return "specification";
}
case 0x48:
{
return "static_link";
}
case 0x49:
{
return "type";
}
case 0x4a:
{
return "use_location";
}
case 0x4b:
{
return "variable_parameter";
}
case 0x4c:
{
return "virtuality";
}
case 0x4d:
{
return "vtable_elem_location";
}
case 0x4e:
{
return "allocated";
}
case 0x4f:
{
return "associated";
}
case 0x50:
{
return "data_location";
}
case 0x51:
{
return "byte_stride";
}
case 0x52:
{
return "entry_pc";
}
case 0x53:
{
return "use_utf8";
}
case 0x54:
{
return "extension";
}
case 0x55:
{
return "ranges";
}
case 0x56:
{
return "trampoline";
}
case 0x57:
{
return "call_column";
}
case 0x58:
{
return "call_file";
}
case 0x59:
{
return "call_line";
}
case 0x5a:
{
return "description";
}
case 0x5b:
{
return "binary_scale";
}
case 0x5c:
{
return "decimal_scale";
}
case 0x5d:
{
return "small";
}
case 0x5e:
{
return "decimal_sign";
}
case 0x5f:
{
return "digit_count";
}
case 0x60:
{
return "picture_string";
}
case 0x61:
{
return "mutable";
}
case 0x62:
{
return "threads_scaled";
}
case 0x63:
{
return "explicit";
}
case 0x64:
{
return "object_pointer";
}
case 0x65:
{
return "endianity";
}
case 0x66:
{
return "elemental";
}
case 0x67:
{
return "pure";
}
case 0x68:
{
return "recursive";
}
case 0x69:
{
return "signature";
}
case 0x6a:
{
return "main_subprogram";
}
case 0x6b:
{
return "data_bit_offset";
}
case 0x6c:
{
return "const_expr";
}
case 0x6d:
{
return "enum_class";
}
case 0x6e:
{
return "linkage_name";
}
default:
{
if(attribute >= 0x2000 && attribute <= 0x3fff)
return "USER_DEFINED_ATTRIBUTE";
else
return "UNRECOGNISED_ATTRIBUTE";
}
}
}
char *dwarfy_form_to_string(unsigned long int form)
{
switch(form)
{
case 0x01:
{
return "addr";
}
case 0x03:
{
return "block2";
}
case 0x04:
{
return "block4";
}
case 0x05:
{
return "data2";
}
case 0x06:
{
return "data4";
}
case 0x07:
{
return "data8";
}
case 0x08:
{
return "string";
}
case 0x09:
{
return "block";
}
case 0x0a:
{
return "block1";
}
case 0x0b:
{
return "data1";
}
case 0x0c:
{
return "flag";
}
case 0x0d:
{
return "sdata";
}
case 0x0e:
{
return "strp";
}
case 0x0f:
{
return "udata";
}
case 0x10:
{
return "ref_addr";
}
case 0x11:
{
return "ref1";
}
case 0x12:
{
return "ref2";
}
case 0x13:
{
return "ref4";
}
case 0x14:
{
return "ref8";
}
case 0x15:
{
return "ref_udata";
}
case 0x16:
{
return "indirect";
}
case 0x17:
{
return "sec_offset";
}
case 0x18:
{
return "exprloc";
}
case 0x19:
{
return "flag_present";
}
case 0x20:
{
return "ref_sig8";
}
default:
{
return "UNRECOGNISED_FORM";
}
}
}
|
SanctaMaria1997/mprof | mprof_util.c | <gh_stars>0
/*
BSD 2-Clause License
Copyright (c) 2019, SanctaMaria1997
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#define _GNU_SOURCE
#include <stdlib.h>
#include <ftw.h>
#include <stdio.h>
#include <string.h>
//#include "dwarfy.h"
//#include "mprof.h"
char *REQUESTED_FILE_NAME;
char *MATCHING_FILE_PATH;
int FILE_PATH_EXISTS;
const char *file_part(const char *path)
{
int last_slash = 0;
int i;
for(i = 0; i < strlen(path); i++)
{
if(path[i] == '/')
{
last_slash = i;
}
}
return path + last_slash + (last_slash ? 1 : 0);
}
int evaluate_item(const char *path, const struct stat *info,const int typeflag, struct FTW *path_info)
{
if (typeflag == FTW_F)
{
if(!strcmp(path + path_info->base,REQUESTED_FILE_NAME))
{
MATCHING_FILE_PATH = strdup(path);
FILE_PATH_EXISTS = 1;
return 1;
}
}
return 0;
}
char *find_file(char *file_name,char *directory)
{
MATCHING_FILE_PATH = 0;
REQUESTED_FILE_NAME = file_name;
FILE_PATH_EXISTS = 0;
nftw(directory,evaluate_item,15,FTW_PHYS);
if(FILE_PATH_EXISTS)
return MATCHING_FILE_PATH;
else
return "";
}
/*
Library *lookup_library(char *name)
{
int i = 0;
while(strlen(LIBMPROF_SHARED_MEM->libraries[i].name))
{
if(!strcmp(file_part(LIBMPROF_SHARED_MEM->libraries[i].name),file_part(name)))
return &LIBMPROF_SHARED_MEM->libraries[i];
i++;
}
return 0;
}*/
|
SanctaMaria1997/mprof | libmprof.h | /*
BSD 2-Clause License
Copyright (c) 2019, SanctaMaria1997
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef LIBMPROF_H
#define LIBMPROF_H
#ifdef LINUX
#include "tree.h"
#elif defined(FREEBSD)
#include <sys/tree.h>
#endif
#define MPROF_TRACE_DEPTH 5
#define TRANSACTION_TYPE_ALLOC 1
#define TRANSACTION_TYPE_FREE 2
#define TRANSACTION_TYPE_GENERIC 3
typedef RB_HEAD(TransactionPointTree,TransactionPoint) TransactionPointTree_t;
typedef RB_HEAD(TransactionPathTree,TransactionPath) TransactionPathTree_t;
typedef RB_HEAD(TransactionPathSortedTree,TransactionPathSorted) TransactionPathSortedTree_t;
typedef RB_HEAD(MemoryBlockTree,MemoryBlock) MemoryBlockTree_t;
typedef RB_HEAD(MemoryBlockSortedTree,MemoryBlockSorted) MemoryBlockSortedTree_t;
typedef RB_HEAD(MemoryBreakdownTree,MemoryBreakdown) MemoryBreakdownTree_t;
typedef RB_HEAD(FunctionBreakdownTree,FunctionBreakdown) FunctionBreakdownTree_t;
typedef RB_HEAD(SortedLibraryTree,SortedLibrary) SortedLibraryTree_t;
typedef struct TransactionPoint TransactionPoint;
struct TransactionPoint
{
int transaction_type;
long int address;
TransactionPathTree_t paths;
RB_ENTRY(TransactionPoint) TransactionPointLinks;
};
int compare_transaction_points(TransactionPoint *a1,TransactionPoint *a2);
RB_PROTOTYPE(TransactionPointTree,TransactionPoint,TransactionPointLinks,compare_transaction_points_by_address);
typedef struct TransactionPath TransactionPath;
typedef struct TransactionPathSorted TransactionPathSorted;
struct AllocationPath
{
unsigned long int current_num_transactions;
unsigned long int current_bytes_allocated;
unsigned long int total_num_transactions;
unsigned long int total_bytes_allocated;
MemoryBlockTree_t memory_blocks;
};
struct FreePath
{
unsigned long int total_num_frees;
unsigned long int total_bytes_freed;
};
struct GenericPath
{
unsigned long int current_num_transactions;
unsigned long int current_bytes_allocated;
unsigned long int total_num_transactions;
unsigned long int total_bytes_allocated;
unsigned long int total_num_frees;
unsigned long int total_bytes_freed;
MemoryBlockTree_t memory_blocks;
};
typedef struct
{
char function_names[MPROF_TRACE_DEPTH][256];
int too_deep;
} Backtrace;
#define TRANSACTION_PATH(FFS)\
struct FFS\
{\
Backtrace *trace;\
TransactionPoint *transaction_point;\
unsigned long int current_num_transactions;\
unsigned long int current_bytes_allocated;\
unsigned long int total_num_transactions;\
unsigned long int total_bytes_allocated;\
unsigned long int total_num_frees;\
unsigned long int total_bytes_freed;\
MemoryBlockTree_t memory_blocks;\
RB_ENTRY(FFS) FFS ## Links;\
};
TRANSACTION_PATH(TransactionPath);
TRANSACTION_PATH(TransactionPathSorted);
int compare_transaction_paths_by_trace(TransactionPath *a1,TransactionPath *a2);
int compare_transaction_paths_by_leaked_bytes(TransactionPathSorted *a1,TransactionPathSorted *a2);
RB_PROTOTYPE(TransactionPathSortedTree,TransactionPathSorted,TransactionPathSortedLinks,compare_transaction_paths_by_name);
RB_PROTOTYPE(TransactionPathSortedTree,TransactionPathSorted,TransactionPathSortedLinks,compare_transaction_paths_by_leaked_bytes);
typedef struct MemoryBlock MemoryBlock;
typedef struct MemoryBlockSorted MemoryBlockSorted;
#define MEMORY_BLOCK(FFS)\
struct FFS\
{\
unsigned long int address;\
size_t size;\
TransactionPath *path;\
RB_ENTRY(FFS) FFS ## Links;\
};
MEMORY_BLOCK(MemoryBlock)
MEMORY_BLOCK(MemoryBlockSorted)
int compare_memory_blocks_by_address(MemoryBlock *mb1,MemoryBlock *mb2);
int compare_memory_blocks_by_size(MemoryBlockSorted *mb1,MemoryBlockSorted *mb2);
RB_PROTOTYPE(MemoryBlockTree,MemoryBlock,MemoryBlockLinks,compare_memory_blocks_by_address);
RB_PROTOTYPE(MemoryBlockSortedTree,MemoryBlockSorted,MemoryBlockSortedLinks,compare_memory_blocks_by_size);
typedef struct MemoryBreakdown MemoryBreakdown;
struct MemoryBreakdown
{
size_t size;
unsigned long int total_num_allocs;
unsigned long int total_bytes_allocated;
unsigned long int total_num_frees;
unsigned long int current_bytes_allocated;
RB_ENTRY(MemoryBreakdown) MemoryBreakdownLinks;
};
int compare_memory_breakdowns(MemoryBreakdown *mb1,MemoryBreakdown *mb2);
RB_PROTOTYPE(MemoryBreakdownTree,MemoryBreakdown,MemoryBreakdownLinks,compare_memory_breakdowns);
typedef struct FunctionBreakdown FunctionBreakdown;
struct FunctionBreakdown
{
char *name;
unsigned long int total_bytes_allocated;
unsigned long int current_bytes_allocated;
unsigned long int num_allocations_small;
unsigned long int num_allocations_medium;
unsigned long int num_allocations_large;
unsigned long int num_allocations_xlarge;
unsigned long int num_frees_small;
unsigned long int num_frees_medium;
unsigned long int num_frees_large;
unsigned long int num_frees_xlarge;
unsigned long int num_calls;
RB_ENTRY(FunctionBreakdown) FunctionBreakdownLinks;
};
int compare_function_breakdowns(FunctionBreakdown *fb1,FunctionBreakdown *fb2);
RB_PROTOTYPE(FunctionBreakdownTree,FunctionBreakdown,FunctionBreakdownLinks,compare_function_breakdowns);
typedef struct SortedLibrary SortedLibrary;
struct SortedLibrary
{
char name[256];
unsigned char *elf;
DWARF_DATA *dwarf;
unsigned long int base_address;
RB_ENTRY(SortedLibrary) SortedLibraryLinks;
};
int compare_sorted_libraries(SortedLibrary *sl1,SortedLibrary *sl2);
RB_PROTOTYPE(SortedLibraryTree,SortedLibrary,SortedLibraryLinks,compare_sorted_libraries);
void memory_breakdown_table_out();
void leak_table_out();
void function_breakdown_table_out();
void *mprof_malloc(size_t size);
void *mprof_calloc(size_t num,size_t size);
void *mprof_realloc(void *mem,size_t size);
void mprof_free(void *mem);
#endif
|
SanctaMaria1997/mprof | test.c | <gh_stars>0
#include <stdlib.h>
#include <stdio.h>
void indirect_leak1(int n);
void indirect_leak2(int n);
void actual_leak(int n);
void a_5019()
{
malloc(5019);
}
int main(int argc,char **argv)
{
a_5019();
for(int k = 0; k < 5; k++)
malloc(10);
for(int k = 0; k < 20; k++)
malloc(40);
for(int k = 0; k < 4; k++)
malloc(300);
exit(0);
puts("Hi from test");
indirect_leak1(123);
puts("Hi again from test");
indirect_leak2(321);
char buff[32];
scanf("%s",buff);
int *p = malloc(20);
free(p);
p = calloc(3,40);
//free(p);
return 0;
}
void indirect_leak1(int n)
{
actual_leak(n);
}
void indirect_leak2(int n)
{
actual_leak(n);
}
void actual_leak(int n)
{
void *p;
p = malloc(n);
if(n == 123)
free(p);
}
|
SanctaMaria1997/mprof | args.c | <reponame>SanctaMaria1997/mprof<filename>args.c
/*
BSD 2-Clause License
Copyright (c) 2019, SanctaMaria1997
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "args.h"
#include <stdio.h>
#include <string.h>
OptionSpec *available_options;
Option options[MAX_NUM_OPTIONS];
NonOption non_options[MAX_NUM_NON_OPTIONS];
void register_options(OptionSpec *ao)
{
available_options = ao;
}
int parse_options(int argc,char **argv)
{
int valid_option = 0;
int expect_arg = 0;
int i,j,k,l;
memset(options,0,MAX_NUM_OPTIONS * sizeof(Option));
memset(non_options,0,MAX_NUM_NON_OPTIONS * sizeof(NonOption));
i = j = k = l = 0;
for(i = 1; i < argc; i++)
{
if(argv[i][0] == '-')
{
j = 0;
valid_option = 0;
while(strlen(available_options[j].name))
{
if(0 == strcmp(argv[i],available_options[j].name) || 0 == strcmp(argv[i],available_options[j].short_name))
{
valid_option = 1;
break;
}
j++;
}
if(!valid_option)
{
return 0;
}
strcpy(options[k].option,argv[i]);
options[k].index = i;
if(available_options[j].takes_arg)
expect_arg = 1;
else
k++;
}
else
{
if(expect_arg)
{
if(argv[i][0] == '-')
return 0;
strcpy(options[k].argument,argv[i]);
k++;
expect_arg = 0;
}
else
{
strcpy(non_options[l].text,argv[i]);
non_options[l].index = i;
l++;
}
}
}
return 1;
}
Option *get_options()
{
return options;
}
NonOption *get_non_options()
{
return non_options;
}
int option_is(char *name,Option *option)
{
int i = 0;
while(strlen(available_options[i].name))
{
if(0 == strcmp(name,available_options[i].name) || 0 == strcmp(name,available_options[i].short_name))
{
if(0 == strcmp(option->option,available_options[i].name) || 0 == strcmp(option->option,available_options[i].short_name))
{
return 1;
}
}
i++;
}
return 0;
}
|
SanctaMaria1997/mprof | mprof.c | /*
BSD 2-Clause License
Copyright (c) 2019, SanctaMaria1997
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/shm.h>
#include <semaphore.h>
#include <fcntl.h>
#include <sys/ptrace.h>
#include <elf.h>
#ifdef LINUX
#include <libdwarf/dwarf.h>
#elif defined(FREEBSD)
#include <dwarf.h>
#endif
#include <getopt.h>
#include "elf_util.h"
#include "mprof_util.h"
#include "args.h"
#include "mprof.h"
#include "dwarfy.h"
#ifdef FREEBSD
#define PTRACE_TRACEME PT_TRACE_ME
#define PTRACE_CONT PT_CONTINUE
#define PTRACE_GETREGS PT_GETREGS
#define PTRACE_PEEKDATA PT_READ_D
#define PTRACE_POKEDATA PT_WRITE_D
#define PTRACE_VM_ENTRY PT_VM_ENTRY
#else
#define r_
#endif
extern char **environ;
LibmprofSharedMem *LIBMPROF_SHARED_MEM;
int SHMID;
int LIBMPROF_NUM_PATCHED_LIBS;
Library *lookup_library(char *name);
FILE *MPROF_OUTPUT_FILE;
char MPROF_OUTPUT_FILE_NAME[256];
sem_t *MPROF_INSTANCE;
sem_t *MPROF_MUTEX;
sem_t *MPROF_MEM_MUTEX;
void patch_function(pid_t pid,unsigned long int orig,unsigned long int wrapper)
{
#ifdef LINUX
ptrace(PTRACE_POKEDATA,pid,(caddr_t)orig,wrapper);
#elif defined(FREEBSD)
int high,low;
low = (int)(wrapper & 0xFFFFFFFF);
high = (int)((wrapper & 0xFFFFFFFF00000000) >> 32);
ptrace(PTRACE_POKEDATA,pid,(caddr_t)orig,low);
ptrace(PTRACE_POKEDATA,pid,(caddr_t)(orig + 4),high);
#endif
}
void patch_mem_functions(pid_t pid,Library *destination,Library *source)
{
char *libc_functions[] = {"malloc","calloc","realloc","free",""};
char *gnu_functions[] = {"g_malloc","g_malloc0","g_realloc","g_try_malloc","g_try_malloc0","g_try_realloc","g_malloc_n","malloc0_n","g_realloc_n","g_free",""};
char **functions;
char patch[256];
unsigned long int relocation;
int i;
if(LIBMPROF_SHARED_MEM->config.gnu)
functions = gnu_functions;
else
functions = libc_functions;
i = 0;
while(0 != strcmp(functions[i],""))
{
strcpy(patch,"mprof");
strcat(patch,"_");
strcat(patch,functions[i]);
if((relocation = get_elf_relocation(destination->elf,functions[i])))
patch_function(pid,
relocation - get_elf_base_address(destination->elf) + destination->base_address,
get_elf_symbol(source->elf,patch) - get_elf_base_address(source->elf) + source->base_address);
i++;
}
}
void strip_so_version_num(char *st)
{
int z = 0;
while(st[z] != 0)
{;
if(st[z] == '.' && st[z+1] == 's' && st[z+2] == 'o')
{
st[z+3] = 0;
break;
}
z++;
}
}
#ifdef LINUX
void load_mem_regions(pid_t pid)
{
FILE *vm_maps;
char pid_str[32];
char path[64];
char module_path[512];
char buff[512];
int i,j,k;
int bytes_read;
char d[128];
int line_offset;
int file_offset;
void *low_address;
void *high_address;
char c;
i = 0;
j = 0;
k = 0;
file_offset = 0;
low_address = 0;
high_address = 0;
sprintf(pid_str,"%d",pid);
strcpy(path,"/proc/");
strcat(path,pid_str);
strcat(path,"/maps");
vm_maps = fopen(path,"rb");
do
{
file_offset = 0;
line_offset = 0;
do
{
fscanf(vm_maps,"%c",&c);
buff[file_offset] = c;
file_offset++;
} while(c != '\n' && !feof(vm_maps));
buff[file_offset] = 0;
module_path[0] = 0;
sscanf(buff,"%lx-%lx %s %s %s %s %n",&low_address,&high_address,d,d,d,d,&bytes_read);
line_offset = bytes_read;
if(buff[line_offset] == '/')
{
sscanf(buff + line_offset,"%s%n",module_path,&bytes_read);
line_offset += bytes_read;
while(buff[line_offset])
{
sscanf(buff + line_offset,"%c",d);
line_offset++;
}
}
for(j = 0; j < k; j++)
{
if(!strcmp(file_part(module_path),file_part(LIBMPROF_SHARED_MEM->libraries[j].name)))
goto skip;
}
if(strlen(module_path) == 0)
goto skip;
LIBMPROF_SHARED_MEM->libraries[k].base_address = (unsigned long int)(low_address);
strcpy(LIBMPROF_SHARED_MEM->libraries[k].name,file_part(module_path));
strip_so_version_num(LIBMPROF_SHARED_MEM->libraries[k].name);
k++;
skip:
k;
} while(!feof(vm_maps));
fclose(vm_maps);
}
#elif defined(FREEBSD)
void load_mem_regions(pid_t pid)
{
struct ptrace_vm_entry entry;
unsigned long int prev_start = 0;
char *mmm = malloc(256);
entry.pve_entry = 0;
entry.pve_start = 0;
entry.pve_path = mmm;
int i,j,k;
i = 0;
j = 0;
k = 0;
do
{
prev_start = entry.pve_start;
entry.pve_pathlen = 256;
ptrace(PTRACE_VM_ENTRY,pid,(caddr_t)(&entry),0);
for(j = 0; j < k; j++)
{
if(!strcmp(file_part(mmm),file_part(LIBMPROF_SHARED_MEM->libraries[j].name)))
goto skip;
}
LIBMPROF_SHARED_MEM->libraries[k].base_address = (unsigned long int)(entry.pve_start);
strcpy(LIBMPROF_SHARED_MEM->libraries[k].name,file_part(mmm));
strip_so_version_num(LIBMPROF_SHARED_MEM->libraries[k].name);
k++;
skip:
i++;
} while(entry.pve_start != prev_start);
}
#endif
int main(int argc,char **argv)
{
pid_t pid;
int result = 1;
int status;
char target_name[512];
Library *target,*libmprof;
/*OptionSpec available_options[] = {{"--stderr",0},{"-t",0},
{"--call-sites",0},{"-c",0},
{"--gnu",0},{"-g",0},
{"--structs",0},{"-s",0},
{"",0}};
*/
Option *options;
NonOption *non_options;
int proj;
int instance;
int i,j;
MPROF_MUTEX = sem_open("/mprof_mutex",O_CREAT,0666,1);
MPROF_INSTANCE = sem_open("/mprof_instance",O_CREAT,0666,0);
MPROF_MEM_MUTEX = sem_open("/MPROF_MEM_MUTEX",O_CREAT,0666,1);
sem_getvalue(MPROF_INSTANCE,&instance);
sem_getvalue(MPROF_MUTEX,&proj);
sem_wait(MPROF_MUTEX);
sem_getvalue(MPROF_MUTEX,&proj);
sprintf(MPROF_OUTPUT_FILE_NAME,"tables.mprof.%d",instance);
MPROF_OUTPUT_FILE = fopen(MPROF_OUTPUT_FILE_NAME,"w");
fclose(MPROF_OUTPUT_FILE);
SHMID = shmget(ftok(MPROF_OUTPUT_FILE_NAME,1),sizeof(LibmprofSharedMem),IPC_CREAT | 0666);
LIBMPROF_SHARED_MEM = shmat(SHMID,0,0);
sem_post(MPROF_MUTEX);
memset(LIBMPROF_SHARED_MEM,0,sizeof(LibmprofSharedMem));
LIBMPROF_NUM_PATCHED_LIBS = 0;
OptionSpec available_options[] = {{"--stderr","-t",0},
{"--call-sites","-c",0},
{"--gnu","-g",0},
{"--structs","-s",0},
{"","",0}};
register_options(available_options);
parse_options(argc,argv);
options = get_options();
non_options = get_non_options();
i = 0;
while(i < non_options[0].index && strlen(options[i].option))
{
if(option_is("--stderr",&options[i]))
{
printf("[mprof] Printing to terminal...\n");
LIBMPROF_SHARED_MEM->config.output_to_stderr = 1;
}
else if(option_is("--call-sites",&options[i]))
{
printf("[mprof] Call sites enabled...\n");
LIBMPROF_SHARED_MEM->config.call_sites = 1;
}
else if(option_is("--gnu",&options[i]))
{
printf("[mprof] Patching GNU glib memory management functions only...\n");
LIBMPROF_SHARED_MEM->config.gnu = 1;
}
else if(option_is("--structs",&options[i]))
{
printf("[mprof] Printing corresponding source code structs...\n");
LIBMPROF_SHARED_MEM->config.structs = 1;
}
i++;
}
strcpy(target_name,non_options[0].text);
strcpy(LIBMPROF_SHARED_MEM->patched_lib_names[LIBMPROF_NUM_PATCHED_LIBS],target_name);
LIBMPROF_NUM_PATCHED_LIBS++;
switch(pid = fork())
{
case -1:
{
fprintf(stderr,"Unable to launch traced process; exiting.\n");
exit(1);
}
case 0:
{
ptrace(PTRACE_TRACEME,0,0,0);
putenv("LD_PRELOAD=/usr/local/lib/libmprof.so");
#ifdef LINUX
execvpe(target_name,argv + non_options[0].index,environ);
#elif defined(FREEBSD)
exect(target_name,argv + non_options[0].index,environ);
#endif
fprintf(stderr,"[mprof] Unable to launch program (%s).\n",target_name);
exit(1);
break;
}
default:
{
waitpid(pid,&status,0);
ptrace(PTRACE_CONT,pid,(caddr_t)1,0);
waitpid(pid,&status,0);
load_mem_regions(pid);
libmprof = lookup_library("libmprof.so");
target = lookup_library(target_name);
target->elf = load_elf(find_file(file_part(target_name),"."));
libmprof->elf = load_elf(find_file("libmprof.so","/usr/local/lib/"));
if(target->elf == 0)
{
fprintf(stderr,"[mprof] Unable to load ELF file \"%s\".",target->name);
exit(1);
}
if(libmprof->elf == 0)
{
fprintf(stderr,"[mprof] Unable to load ELF file \"%s\".",libmprof->name);
exit(1);
}
patch_mem_functions(pid,target,libmprof);
j = 0;
while(strlen(LIBMPROF_SHARED_MEM->libraries[j].name))
{
if( strcmp(LIBMPROF_SHARED_MEM->libraries[j].name,"placeholder.so"))
{
LIBMPROF_SHARED_MEM->libraries[j].elf = load_elf(find_file(LIBMPROF_SHARED_MEM->libraries[j].name,"."));
if(LIBMPROF_SHARED_MEM->libraries[j].elf == 0)
{
fprintf(stderr,"[mprof] Note: unable to locate shared object \"%s\" in current directory hierarchy.\n",LIBMPROF_SHARED_MEM->libraries[j].name);
goto cont;
}
if(strcmp(LIBMPROF_SHARED_MEM->libraries[j].name,"libmprof.so"))
{
fprintf(stderr,"[mprof] Patching \"%s\"...\n",LIBMPROF_SHARED_MEM->libraries[j].name);
patch_mem_functions(pid,&LIBMPROF_SHARED_MEM->libraries[j],libmprof);
}
}
cont:
j++;
}
ptrace(PTRACE_CONT,pid,(caddr_t)1,0);
for(;;)
{
waitpid(pid,&status,0);
if(WIFSTOPPED(status))
{
ptrace(PTRACE_CONT,pid,(caddr_t)1,0);
}
else if(WIFEXITED(status))
{
result = WEXITSTATUS(status);
break;
}
}
}
}
if(LIBMPROF_SHARED_MEM->config.output_to_stderr)
remove(MPROF_OUTPUT_FILE_NAME);
shmdt(LIBMPROF_SHARED_MEM);
shmctl(SHMID,IPC_RMID,0);
fprintf(stderr,"[mprof] Program exited with code %d.\n",result);
return 0;
}
Library *lookup_library(char *name)
{
int i = 0;
while(strlen(LIBMPROF_SHARED_MEM->libraries[i].name))
{
if(!strcmp(file_part(LIBMPROF_SHARED_MEM->libraries[i].name),file_part(name)))
{
return &LIBMPROF_SHARED_MEM->libraries[i];
}
i++;
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.